php regular expression memo

\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 ‘-‘.

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Comments are closed, but trackbacks and pingbacks are open.