note 91672 modified in function.str-ireplace by danbrown

From: Date: Mon, 22 Jun 2009 15:10:08 +0000
Subject: note 91672 modified in function.str-ireplace by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-157239@lists.php.net to get a copy of this message
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 // http://devboard.viathinksoft.de/viewtopic.php?f=34&t=771 // Bugfix-Release #3 (June, 22th 2009) 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 $rest = $subject; $result = ''; while (stripos($rest, $findme) !== false) { $pos = stripos($rest, $findme); // Remove the wanted string from $rest and append it to $result $result .= substr($rest, 0, $pos); $rest = substr($rest, $pos, strlen($rest)-$pos); // Remove the wanted string from $rest and place it correctly into $result $result .= str_replace('$1', substr($rest, 0, strlen($findme)), $replacewith); $rest = substr($rest, strlen($findme), strlen($rest)-strlen($findme)); } // After the last match, append the rest $result .= $rest; return $result; } ?> --was-- My function ext_str_ireplace() from http://www.php.net/manual/de/function.str-ireplace.php#86099 had a few heavy bugs, which I finally found and fixed: <?php // http://devboard.viathinksoft.de/viewtopic.php?f=34&t=771 // Bugfix-Release #3 (June, 22th 2009) 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 $rest = $subject; $result = ''; while (stripos($rest, $findme) !== false) { $pos = stripos($rest, $findme); // Remove the wanted string from $rest and append it to $result $result .= substr($rest, 0, $pos); $rest = substr($rest, $pos, strlen($rest)-$pos); // Remove the wanted string from $rest and place it correctly into $result $result .= str_replace('$1', substr($rest, 0, strlen($findme)), $replacewith); $rest = substr($rest, strlen($findme), strlen($rest)-strlen($findme)); } // After the last match, append the rest $result .= $rest; return $result; } ?> http://php.net/manual/en/function.str-ireplace.php

« previous php.notes (#157239) next »