How do I use preg_match() to extract words marked with ## from a string and then put them in html tag(s)?

45 Views Asked by At

How to get from here:

The #quick# brown fox jumps over the #lazy# dog

to here:

The span-tag quick /span-tag brown fox jumps over the span-tag lazy /span-tag dog

?

And sometimes it`s only:

The quick brown fox jumps over the #lazy# dog

so a dynamic solution would be great.

My output right now is only quick

<?php preg_match("/(?<=#).*?(?=#)/", "The #quick# brown fox jumps over the #lazy# dog", $match);
  var_dump($match)
?>
1

There are 1 best solutions below

1
Rob Eyre On

Perhaps using preg_replace and a simpler pattern would work:

$str = 'The #quick# brown fox jumps over the #lazy# dog';
$newStr = preg_replace('/#([^#]*)#/', '<span>$1</span>', $str);

Produces

The <span>quick</span> brown fox jumps over the <span>lazy</span> dog