note 101814 added to function.preg-replace
| From: | highlighter at osu1 dot php dot net | Date: | Wed, 12 Jan 2011 16:37:38 +0000 |
| Subject: | note 101814 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-175679@lists.php.net to get a copy of this message | ||
Accent independent highlighting of text, UTF-8 safe:
<?php
function prepare_search_term($str,$delim='#') {
$search = preg_quote($str,$delim);
$search = preg_replace('/[aà áâãåäæ]/iu',
'[aà áâãåäæ]', $search);
$search = preg_replace('/[eèéêë]/iu', '[eèéêë]',
$search);
$search = preg_replace('/[iìÃîï]/iu', '[iìÃîï]',
$search);
$search = preg_replace('/[oòóôõöø]/iu',
'[oòóôõöø]', $search);
$search = preg_replace('/[uùúûü]/iu', '[uùúûü]',
$search);
// add more characters...
return $search;
}
function highlight($searchtext, $text) {
$search = prepare_search_term($searchtext);
return preg_replace('#' . $search . '#iu', '<span
style="background-color:red">$0</span>', $text);
}
$testtext = 'cafe cáfé cà fè CAFE CÃFà CÃFà cà fé cáfè
CÃFÃ CÃFÃ';
echo highlight('cafe',$testtext) . '<br />';
echo highlight('cáfé',$testtext) . '<br />';
echo highlight('CAFE',$testtext) . '<br />';
echo highlight('CÃFÃ',$testtext) . '<br />';
?>
This function finds and highlights all words in $testtext with (e.g.) every single word in $testtext
as input. Useful if you retrieved a text from a MySQL database and want to highlight the search term
accent-independently.
The main trick is in "prepare_search_term": Every single character of the search pattern
(1st parameter of preg_replace) in the search term is replaced by the whole string in the 2nd
parameter, which then in function "highlight" acts as the search pattern for replacement
there. Hope you find this useful.
----
Server IP: 217.160.235.204
Probable Submitter: 77.20.144.189
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace.php
Edit -- https://master.php.net/note/edit/101814
Del: integrated -- https://master.php.net/note/delete/101814/integrated
Del: useless -- https://master.php.net/note/delete/101814/useless
Del: bad code -- https://master.php.net/note/delete/101814/bad+code
Del: spam -- https://master.php.net/note/delete/101814/spam
Del: non-english -- https://master.php.net/note/delete/101814/non-english
Del: in docs -- https://master.php.net/note/delete/101814/in+docs
Del: other reasons-- https://master.php.net/note/delete/101814
Reject -- https://master.php.net/note/reject/101814
Search -- https://master.php.net/manage/user-notes.php