note 79273 added to function.preg-match
| From: | boyan7640 at gmail dot com | Date: | Mon, 19 Nov 2007 10:19:14 +0000 |
| Subject: | note 79273 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-132394@lists.php.net to get a copy of this message | ||
If you try to find the offset when searching in UTF-8 string (containing multibyte characters, like
cyrillic characters) with preg_match, using the PREG_OFFSET_CAPTURE flag, you may have different
result from what you expected.
First of all you must compiled PHP with Multibyte Support (mbstring). Then you must configure to use
Multibyte Support functions (mb_*) or turn on some php Runtime Configurations (php.ini, apache vhost
conf file, .htaccess or somewhere else):
php_value default_charset UTF-8
php_value mbstring.func_overload 7
php_value mbstring.internal_encoding UTF-8
php_value mbstring.detect_order UTF-8
When using preg_match with PREG_OFFSET_CAPTURE flag and UTF-8 string the function will count bytes
and NOT characters, so 2 bytes but NOT 1 character for some multibyte character. That's way the
offset will be more than what you expected.
My simple solution is using mb_strpos:
...
preg_match($pattern, $found_text, $matches, PREG_OFFSET_CAPTURE);
// This will convert $matches[0][1] multibyte byte length to multibyte character length (UTF-8)
$matches[0][1] = mb_strpos($found_text, $matches[0][0]);
...
P.S. The $pattern variable must use "/u" switch for Unicode!!!
-------------------------------------------------
PHP Version 5.2.4
Multibyte regex (oniguruma) version 4.4.4
-------------------------------------------------
----
Server IP: 195.149.248.161
Probable Submitter: 77.70.52.112
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- https://master.php.net/note/edit/79273
Del: integrated -- https://master.php.net/note/delete/79273/integrated
Del: useless -- https://master.php.net/note/delete/79273/useless
Del: bad code -- https://master.php.net/note/delete/79273/bad+code
Del: spam -- https://master.php.net/note/delete/79273/spam
Del: non-english -- https://master.php.net/note/delete/79273/non-english
Del: in docs -- https://master.php.net/note/delete/79273/in+docs
Del: other reasons-- https://master.php.net/note/delete/79273
Reject -- https://master.php.net/note/reject/79273
Search -- https://master.php.net/manage/user-notes.php