note 66124 added to function.preg-match
| From: | ickata at ickata dot net | Date: | Mon, 15 May 2006 11:47:20 +0000 |
| Subject: | note 66124 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-111314@lists.php.net to get a copy of this message | ||
When you want to perform a case-insensitive match,
you use the following code to do it:
<?php
preg_match ("/word/i",$string);
?>
However, there is a problem if you use cyrillic characters
and your host server is Linux - no matter that you use the
"i" parameter after the filter. This is really bad for
Russians and Bulgarians, but there is a solution:
<?php
// Firstly, we need to define some functions which will
// convert our cyrillic string to uppercase or lowercase
// - strtolower() and strtoupper() do not work if your string
// contains cyrillic characters and your server is Linux.
function cstrtolower($str) {
return strtr($str,
"ÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐРСТУФХЦЧШЩЪЬЮЯ",
"абвгдежзийклмнопÑÑÑÑÑÑ
ÑÑÑÑÑÑÑÑ");
}
function cstrtoupper($str) {
return strtr($str,
"абвгдежзийклмнопÑÑÑÑÑÑ
ÑÑÑÑÑÑÑÑ",
"ÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐÐРСТУФХЦЧШЩЪЬЮЯ");
}
// Now we have to define a function which will break apart
// the word for which we are searching in the string in
// groups - lowercase and uppercase in a group, for example
// if we are searching for "word", our filter must looks like
// this: "/[Ww][Oo][Rr][Dd]/"
function createFilter ($string) {
$string = cstrtolower($string);
for ($i=0;$i<strlen($string);$i++) {
$letter_small = substr($string,$i,1);
$letter_big = cstrtoupper($letter_small);
$newstr .= â[â.$letter_small.$letter_big.â]â;
}
return $newstr;
}
// And we are ready to perform the match:
$string = "Това е ÑекÑÑ Ð½Ð°
киÑилиÑа";
$word = "ТеÐÑÑ";
if (preg_match("/".createFilter($word)."/",$string))
echo "A match was found.";
else echo "A match was NOT found!";
?>
And something else - if you want to perform a match for a
whole word, do not use "/\bword\b/", better that:
<?php
preg_match ("/[^A-Za-zÐ-Яа-Ñ]".createFilter("word")
."[^A-Za-zÐ-Яа-Ñ]/", $text);
?>
Hope this will help someone!
----
Server IP: 195.149.248.161
Probable Submitter: 85.187.161.147
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- http://master.php.net/note/edit/66124
Del: integrated -- http://master.php.net/note/delete/66124/integrated
Del: useless -- http://master.php.net/note/delete/66124/useless
Del: bad code -- http://master.php.net/note/delete/66124/bad+code
Del: spam -- http://master.php.net/note/delete/66124/spam
Del: non-english -- http://master.php.net/note/delete/66124/non-english
Del: in docs -- http://master.php.net/note/delete/66124/in+docs
Del: other reasons-- http://master.php.net/note/delete/66124
Reject -- http://master.php.net/note/reject/66124
Search -- http://master.php.net/manage/user-notes.php