note 33425 modified in function.str-replace by aidan

From: Date: Fri, 25 Jun 2004 06:06:14 +0000
Subject: note 33425 modified in function.str-replace by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-71639@lists.php.net to get a copy of this message
here is a function to highlight a part of a string. Unlike str_replace, it is both case insensitive, and maintains the case of the highlighted text. <?php function highlight($x,$var) {//$x is the string, $var is the text to be highlighted if ($var != "") { $xtemp = ""; $i=0; while($i<strlen($x)){ if((($i + strlen($var)) <= strlen($x)) && (strcasecmp($var, substr($x, $i, strlen($var))) == 0)) { $xtemp .= "<b>" . substr($x, $i , strlen($var)) . "</b>";//this version bolds the text. you can replace the html tags with whatever you like. $i += strlen($var); } else { $xtemp .= $x{$i}; $i++; } } $x = $xtemp; } return $x; } ?> Example: <?php $string = "AaBbCcDd"; $string = highlight($string, "bc"); echo $string; //AaB<b>bC</b>cDd ?> --was-- here is a function to highlight a part of a string. Unlike str_replace, it is both case insensitive, and maintains the case of the highlighted text. function highlight($x,$var) {//$x is the string, $var is the text to be highlighted if ($var != "") { $xtemp = ""; $i=0; while($i<strlen($x)){ if((($i + strlen($var)) <= strlen($x)) && (strcasecmp($var, substr($x, $i, strlen($var))) == 0)) { $xtemp .= "<b>" . substr($x, $i , strlen($var)) . "</b>";//this version bolds the text. you can replace the html tags with whatever you like. $i += strlen($var); } else { $xtemp .= $x{$i}; $i++; } } $x = $xtemp; } return $x; } Example: $string = "AaBbCcDd"; $string = highlight($string, "bc"); echo $string; //AaB<b>bC</b>cDd http://php.net/manual/en/function.str-replace.php

« previous php.notes (#71639) next »