3

I am trying to add a span tag to the last word of a string. It works if the string has no special characters. I can't figure out the correct regex for it.

$string = "Onun Mesajı";
echo preg_replace("~\W\w+\s*\S?$~", ' <span>' . '\\0' . '</span>', $string);

Here is the Turkish character set : ÇŞĞÜÖİçşğüöı

DavidRR
  • 18,291
  • 25
  • 109
  • 191
Dejavu
  • 703
  • 3
  • 9
  • 26

3 Answers3

4

You need to use /u modifier to allow processing Unicode characters in the pattern and input string.

preg_replace('~\w+\s*$~u', '<span>$0</span>', $string); 
                       ^

Full PHP demo:

$string = "Onun Mesajı";
echo preg_replace("~\w+\s*$~u", '<span>$0</span>', $string);

Also, the regex you need is just \w+\s*$:

  • \w+ - 1 or more alphanumerics
  • \s* - 0 or more whitespace (trailing)
  • $ - end of string

Since I removed the \W from the regex, there is no need to "hardcode" the leading space in the replacement string (removed, too).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

You should use the u modifier for regular expressions to set the engine into unicode mode:

<?php
$subject = "Onun äöüß Mesajı";
$pattern = '/\w+\s*?$/u';
echo preg_replace($pattern, '<span>\\0</span>', $subject);

The output is:

Onun äöüß <span>Mesajı</span>
arkascha
  • 41,620
  • 7
  • 58
  • 90
0

This regex will do the trick for you, and is a lot shorter then the other solutions:

[ ](.*?$)

Here is an example of it:

$string = "Onun Mes*ÇŞĞÜÖİçşğüöıajı";
echo preg_replace('~[ ](.*?$)~', ' <span>' .'${1}'. '</span>', $string);

Will echo out:

Onun <span>Mes*ÇŞĞÜÖİçşğüöıajı</span>

The way this regex works is that we look for any characters without space in lazy mode [ ].*?.
then we add the $ identifier, so it matches from the end of the string instead.

Oliver Nybroe
  • 1,828
  • 22
  • 30
  • 1
    could you please explain why this works? Might help OP more, if he understands how the regex works. Thanks :-) – Lino Dec 04 '15 at 13:31
  • Why should the OP try this? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO. – Jay Blanchard Dec 04 '15 at 13:36
  • Yeah sorry @Lino, just extended my answer with some text to explain it – Oliver Nybroe Dec 04 '15 at 13:37