Re: Re: string highlight

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Rory Browne wrote:
On 6/8/05, John Nichel <john@xxxxxxxxxxxx> wrote:

Rory Browne wrote:

On 6/8/05, David Duong <david@xxxxxxxxxxx> wrote:


Sebastian wrote:


i'm looking for a function that can highlight certain search terms in a
string. anyone have something already made that i can plugin to my
exisiting code?

I found a couple but they do not work very well.. some break html code
if the string contains the keywords in the html.

thanks.

You can use str_replace to "highlight" the search terms.

For example, you could use the following code for each search term (this
function also accepts arrays, see http://php.net/str_replace):

str_replace ($search_term, "<b>$search_term</b>", $body_text);


Bad idea. Very bad idea.

for example ( using bold to highlight ):
<?pseudo_code

$html = "<html><body>I want to hightlight the word body in this text.
</body></html>";
$search = "body";

$output = str_replace($search, "<b>$search</b>", $html);
// $output == "<html><<b>body</b>>I want to hightlight the word
<b>body</b> in this text. </<b>body</b>></html>";

// see what I mean?
?>

Good catch Rory.  A regex replace would work better here.

$search = "body";
$find = "/\b" . $search . "\b/";
preg_replace ( $find, "<b>" . $search . "</b>", $html );


I don't think so. If I'm reading your code correctly you still have
the same problem, as I outlined above. There is no simple solution to

John is using \b in his regexp to denote a word boundary - I don't believe
< counts as a boundary char therefore niether '<body>' or '<body bla="bla">'
would be preg_replace()'d

this. It either involves advanced regex(more advanced than my
understanding of it), or a proper parser.

<?pseudo_code

function highlight_html_string($needle, $haystack);

$retval = "";
$i = 0;
while($i < strlen($haystack)){
$str = get_text_between_certain_point_and_first_instance_of_<($i); $str = preg_replace(what john said above);
  $str .= get_tag_text($i);
  $retval .= $str;
  $i += strlen($str);
}

return $retval;
?>

--
John C. Nichel
ÜberGeek
KegWorks.com
716.856.9675
john@xxxxxxxxxxxx

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php





--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux