3

I need to highlight my site content based on a phrase like: "fire and water". I need to put <b> tags around the phrase wherever it exists completely. And if the words appear individually (not in complete form) they should get a <b> tag. For example, if the content is:

The world is made of three elements fire and water and air. Fire is hot and water is wet.

The result should be:

The world is made of three elements `<b>`fire and water`</b>` `<b>`and`</b>` air. `<b>`Fire`</b>` is hot `<b>`and`</b>` `<b>`water`</b>` is wet.

I tried using:

$output = preg_replace("/("fire and water)/i", '`<b>`$1`</b>`', $content);   
$output = preg_replace("/(fire|and|water)/i", '`<b>`$1`</b>`', $ouput);

However this produces extra (and unwanted) <b> tags when the full phrase appears in the content causing a result like this:

`<b><b>`fire`</b>` `<b>`and`</b>` `<b>`water`</b></b>`

I know this won't display any differently on the screen than

`<b>`fire and water`</b>`

However, big problems are caused when the search phrase contains a ' / '. There must be a way in regex to highlight the full phrase and individual words without doing both at once.

Gary
  • 13,303
  • 18
  • 49
  • 71
Meyer Auslander
  • 349
  • 1
  • 10

1 Answers1

3

The solution is probably much simpler than you thought:

$input  = 'The world is made of three elements fire and water and air. Fire is hot and water is wet.';

$output = preg_replace("/(fire and water|fire|and|water)/i", '<b>$1</b>',$input);

echo $output;

And the output is:

The world is made of three elements fire and water and air. Fire is hot and water is wet.

The source looks like this:

The world is made of three elements <b>fire and water</b> <b>and</b> air. <b>Fire</b> is hot <b>and</b> <b>water</b> is wet.

The elements are processed in the order they are in.

See also: Escaping a forward slash in a regular expression

KIKO Software
  • 15,283
  • 3
  • 18
  • 33