note 19063 deleted from function.str-replace by alindeman
| From: | alindeman@php.net | Date: | Sat, 17 May 2003 22:05:13 +0000 |
| Subject: | note 19063 deleted from function.str-replace by alindeman | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-48287@lists.php.net to get a copy of this message | ||
Note Submitter: dave@[nospam]netready.biz
----
Here's my implementation of the stri_replace function. I didn't like firewire's
version because it used recursion, I think this is probably faster...
function stri_replace( $find, $replace, $string )
{
$parts = explode( strtolower($find), strtolower($string) );
$pos = 0;
foreach( $parts as $key=>$part ){
$parts[ $key ] = substr($string, $pos, strlen($part));
$pos += strlen($part) + strlen($find);
}
return( join( $replace, $parts ) );
}
Below is a similar function which highlights a particular part of a string (I needed this to
highlight non-case sensitive search results for display). The clever part is that when it
highlights it keeps the proper case of the string. (Modify the HTML part for your preferred
highlight settings!)
function highlight( $needle, $haystack )
{
$parts = explode( strtolower($needle), strtolower($haystack) );
$pos = 0;
foreach( $parts as $key=>$part ){
$parts[ $key ] = substr($haystack, $pos, strlen($part));
$pos += strlen($part);
$parts[ $key ] .= '<FONT
COLOR="#009000"><B>'.substr($haystack, $pos,
strlen($needle)).'</B></FONT>';
$pos += strlen($needle);
}
return( join( '', $parts ) );
}