\b is kind of special, it is not a character, neither a class of characters. It represents a change from a word character(letters, numbers, underscore) to a non-word character(or end of a line), or a change from a non-word character(or beginning of a line) to word character. That is why it is called word boundary.
utf-8 mode
By default, the basic unit that is taken to match against the pattern is a byte. So,
$text="ab汉";
$text=preg_replace('~.$~', '-', $text);
echo $text;
the above code does not replace the last Chinese character with ‘-‘, but replace the last byte with ‘-‘. You will see garbled output. The result $text still has 5 bytes as the original $text. To take a unicode character to do the match, you need the u modifier:
$text="ab汉";
$text=preg_replace('~.$~'u, '-', $text);
echo $text;
Now the result is “ab-” (3 bytes). The Chinese character which occupies 3 bytes is replaced with one ‘-‘.
Comments are closed, but trackbacks and pingbacks are open.