Hi all,

I'm trying to make a little search using REGEX.

My code is as follow:

	$pattern = "/(" . $dHighlight . ")/";
	$replace = "<span class=\"coolio\">$dHighlight</span>";
	$daOutput =	preg_replace($pattern, $replace, $daOutput);

Where $dHighlight is simply what I sent from a INPUT TEXTBOX...

Now the problem is this, let's say I search for HELL in my string. It will not only match HELL but HELLO and SHELL also. However, I just want to replace words that is exactly HELL. So what can I do to fix this?

Thanks 🙂

    well...you want to assert in your pattern that 'hell' would be a word. that would mean your pattern would:

    a) have to be at the very beginning of the searched text or preceded by white space

    and

    b) would have to be at the very end of the searched text or followed by white space.

    i think this might work but i'm not sure:

    $pattern = "/(|\s)(" . $dHighlight . ")(\s|$)/";

    sadly, I have not mastered regular expressions. You might be able to check out highlighting code in phpBB's source code. Or maybe search this forum for 'highlight'.

    Ultimately, if you want to write regular expressions yourself, you'll need to set up some kind of script for testing them.

      \b means word boundary in regexplish. Regexplish is a word I've just made up and means nothing much.

        Example string would be: "Good morning, hello , I'm going to hell to grab a shell"

        Ok, it doesn't make any sense, but when a user performs a search for hell, only hell should be highlighted.

        Thanks for both of your answers, I'll try them out !

          Do you really need regular expressions?

          Why not just do something like this:

          $output = stri_replace($word, "highlight syntax" . $word . "/highlight syntax", $output);
          

          --FrosT

            Well, because that doesn't solve my problem...

            It will still capture and replace HELL HELLO and SHELL
            Isn't that obvious?

              Anyway, I'm not home yet, so can't really try to \b as suggested. I've looked around and see that some CMS(mambo,joomla) just limits its search with a minimum of 3 characters. I guess that would work to solve the non-logical highlights.

                Great, \b works PERFECT, thanks
                So simple, yet so elegant.

                  Write a Reply...