Page 1 of 1

Highlight parts within a string [SOLVED]

Posted: Fri Oct 27, 2006 8:35 pm
by pgolovko
The following function was pulled from the PHP.net web site:
http://www.php.net/manual/en/function.s ... .php#33425

Code: Select all

function highlight($x,$var) {
   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>"; 
                   $i += strlen($var); 
           } 
           else { 
               $xtemp .= $x{$i}; 
               $i++; 
           } 
       } 
       $x = $xtemp; 
   } 
   return $x; 
}
It works almost perfectly. The problem is if $var = "free software" and $x is the following text:

Code: Select all

Script Installation, trouble installing web scripts, perl scripts, Downloads, Free Software Download, Free Ware Download, Free Webmaster Tools - Apply Tools FREE WEBMASTER DOWNLOADS | FREE SOFTWARE DOWNLOAD | FREE WARE DOWNLOAD | FREE WEBMASTER TOOLS Your Ad Here Search Features
the the function will only highlight free software, and not each word free and/or software.
I know that I need to break $var into pieces and then highlight them individually, but I dont know how to do it. Can anyone show me how?

Thank you in advance!

Posted: Fri Oct 27, 2006 8:54 pm
by feyd
explode() maybe.

Posted: Fri Oct 27, 2006 9:11 pm
by printf
In this case a regex would be faster!

Code: Select all

<?php

function highlight( $str, $var )
{
	$var = array_diff ( array_map ( 'trim', explode ( ' ', trim ( $var ) ) ), array ( '' ) );

	return preg_replace ( "/\b(" . implode ( ' ', $var ) . "|" . implode ( '|', $var ) . ")\b/i", "<b>\\1</b>", $str );
}

$str = 'Script Installation, trouble installing web scripts, perl scripts, Downloads, Free Software Download, Free Ware Download, Free Webmaster Tools - Apply Tools FREE WEBMASTER DOWNLOADS | FREE SOFTWARE DOWNLOAD | FREE WARE DOWNLOAD | FREE WEBMASTER TOOLS Your Ad Here Search Features'; 

$var = 'free software';

echo highlight ( $str, $var );

?>

printf

Posted: Fri Oct 27, 2006 9:17 pm
by pgolovko
Thank you, that does exactly what I need.