Include tag in the first word of a string

7

I do not know much about 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

It looks like this:

<span>constru</span>ções importantes
    
asked by anonymous 17.10.2014 / 21:52

1 answer

5

I suggest you look up this blank and "cut" the sentence out there. In this case this regex suffices:

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

Example: link

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

What this regex does is capture - using () all content that is not a white space. Using ^ within [] means negation, and \s for white space. The + indicates 1 or more times. Using \s at the end is an idea that works if you never have a title to end up with white space.

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

Example: link

    
17.10.2014 / 22:38