Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: case-insensitive preg_replace of a cyrillic string in UTF8

I have a PHP 5.3 script displaying users of my web site and would like to replace a certain Russian city (stored in UTF8 in PostgreSQL 8.4.7 database + CentOS 5.5/64 bits Linux) by its older name (it is an insider joke):

preg_replace('/Волгоград/iu', 'Сталинград', $city);

Unfortunately this only works for exact matches: Волгоград.

This does not work for other cases, like ВОЛГОГРАД or волгоград.

If I modify my source code to

preg_replace('/[Вв]олгоград/iu', 'Сталинград', $city);

then it will catch the 2nd case above.

Does anybody know what it going on and how to fix it (assuming I don't want to write [Xx] for every letter)?

Thank you! Alex

UPDATE:

# rpm -qa|grep php
php53-bcmath-5.3.3-1.el5
php53-gd-5.3.3-1.el5
php53-common-5.3.3-1.el5
php53-pdo-5.3.3-1.el5
php53-mbstring-5.3.3-1.el5
php53-xml-5.3.3-1.el5
php53-5.3.3-1.el5
php53-cli-5.3.3-1.el5
php53-pgsql-5.3.3-1.el5

# rpm -qa|grep pcre
pcre-6.6-2.el5_1.7
like image 865
Alexander Farber Avatar asked Dec 03 '22 02:12

Alexander Farber


2 Answers

I cannot reproduce your issue with a PHP 5.3.3 (PHP 5.3.3-1ubuntu9.3 with Suhosin-Patch (cli)):

$str1 = 'Волгоград';
$str2 = 'ВОЛГОГРАД';
$str3 = 'волгоград';

var_dump(preg_replace('/Волгоград/iu', 'Сталинград', $str1));
var_dump(preg_replace('/Волгоград/iu', 'Сталинград', $str2));
var_dump(preg_replace('/Волгоград/iu', 'Сталинград', $str3));

outputs

string(20) "Сталинград"
string(20) "Сталинград"
string(20) "Сталинград"

Which PCRE version is your PHP using? Check you phpinfo() for the pcre-section. That's the one on my system:

...
pcre

PCRE (Perl Compatible Regular Expressions) Support => enabled
PCRE Library Version => 8.02 2010-03-19
...
like image 174
Stefan Gehrig Avatar answered Dec 18 '22 09:12

Stefan Gehrig


You can skip the regex, it worked for me in PHP 5.2.11 :)

$city = 'Unfortunately this only works for exact matches: Волгоград.

This does not work for other cases, like ВОЛГОГРАД or волгоград.';

echo str_ireplace('Волгоград', '[found]', $city);

Output

"Unfortunately this only works for exact matches: [found].

This does not work for other cases, like [found] or [found]."

This intrigued me, so I asked a question.

like image 34
alex Avatar answered Dec 18 '22 09:12

alex