Include tag in the first word of a string

Asked

Viewed 117 times

7

I don’t have much knowledge of regex, so I got this rule ready.

$break_title = preg_replace('/(?<=\>)\b\w*\b|^\w*\b/', '<span>$0</span>', $title);
return $break_title;

The problem is that it does not recognize the cedilla, so the string below:

construções importantes

Stay like this:

<span>constru</span>ções importantes
  • Can you explain what the pattern is? What are the values that $title can have? The special and particular characteristics of each language do not really fit in the regex that has.

  • @Sergio Title values will be dynamic. So I have to predict the use of accented letters and with cedilla.

  • 1

    Have you tested \p{L}?

  • @Sergio Which part should I replace?

  • 1

    Perhaps this is enough: http://ideone.com/ABs2z5 is what you are looking for?

  • 1

    @Sergio worked! And it was much simpler huh. Put as answer.

Show 1 more comment

1 answer

5


I suggest you look for that blank space and "cut" the sentence out there. In that case just this regex:

/([^\s]+)\s/

Example: http://ideone.com/ABs2z5

$title = 'construções importantes';
echo preg_replace('/([^\s]+)\s/', '<span>$0</span>', $title);

What this regex does is capture - using () all content other than a white space. Using the ^ inside [] means denial, and \s to white space. The + specify 1 or more times. Using \s at the end is an idea that works if you never have a title ending with white space.

Maybe it’s better do /^([^\s]+)\s/ which in this case says that the string starts without a space at the beginning.

Example: http://ideone.com/ntKNNv

Browser other questions tagged

You are not signed in. Login or sign up in order to post.