note 86099 deleted from function.str-ireplace by danbrown
| From: | danbrown@php.net | Date: | Mon, 22 Jun 2009 15:09:46 +0000 |
| Subject: | note 86099 deleted from function.str-ireplace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-157238@lists.php.net to get a copy of this message | ||
Note Submitter: info at daniel-marschall dot de
----
If you want to keep the original capitalization when replacing some text (e.g. for highlighting the
search-string in the the search result), you can use this code I wrote:
<?php
function ext_str_ireplace($findme, $replacewith, $subject)
{
// Replaces $findme in $subject with $replacewith
// Ignores the case and do keep the original capitalization by using $1 in $replacewith
// Required: PHP 5
return substr($subject, 0, stripos($subject, $findme)).
str_replace('$1', substr($subject, stripos($subject, $findme), strlen($findme)),
$replacewith).
substr($subject, stripos($subject, $findme)+strlen($findme));
}
?>
Example for using:
<?php
$search = 'replaceme';
$text = 'Please RePlaCeMe, OK?';
// Will print "RePlaCeMe" with red color, but after this it would be
"replaceme", not "RePlaCeMe"
$replace = '<font color="#FF0000">'.$search.'</font>';
echo str_ireplace($search, $replace, $text);
// Will print "RePlaCeMe" with red color
$replace = '<font color="#FF0000">$1</font>';
echo ext_str_ireplace($search, $replace, $text);
?>