What is the correct way of keeping spaces, Latin and Cyrillic characters with preg_replace, in PHP 7.4.*?

Viewed 92

Consider the following.

function cleanText($text) {
    return preg_replace("/[^0-9\p{Latin}\p{Cyrillic}\.\-\_\s+]+/u","",$text);
}
$tmp = "intro_|_text  Mary had a little lamb, we'll be right back   123456789  абвгдђежзијкл     ,./'*     αβγδε    šđ";
echo cleanText($tmp);

Expected output is (as seen on both phpfiddle.org, and repl.it):

intro__text Mary had a little lamb well be right back 123456789 абвгдђежзијкл . šđ

However, Xampp with PHP 7.4.8, and this site return the following (the latter with every PHP 7.4.*):

aMaryhadalittlelambwellberightback123456789абнллклл.šđ

If \p{Latin}\p{Cyrillic} is removed, the spaces are kept. What would be the correct way of having both single spaces and the specific alphabets inside preg_replace?

1 Answers

You may use \p{L} instead of the the Unicode properties whose support seems to be broken here.

You can use

preg_replace('/[^0-9\\p{L}\\s._+-]+/u', '', $text)

Also note that it is safer to use - at the end of the character class, so as not to escape it. . and _ do not need escaping either, _ is a word char and . loses its special meaning inside a character class.

Related