fork(2) download
  1. <?php
  2.  
  3. function highlight_phrases($string, $phrases, $tag = 'strong')
  4. {
  5. usort($phrases, function($a,$b){
  6. return strlen($b)-strlen($a);
  7. });
  8. print_r($phrases);
  9. $pattern = '/' . implode("|", array_map(function ($x) {
  10. return preg_quote($x, '/');
  11. }, $phrases)) . '/i';
  12. echo "\n$pattern";
  13. return preg_replace($pattern, '<' . $tag . '>$0</' . $tag . '>', $string);
  14. }
  15.  
  16. $phrases = ['iphone 7', 'iphone 7 plus'];
  17. $s = "This is some text about the iPhone 7 and this i really a nice peace of engineering. We are now talking about the iPhone 7 Plus, which is very big!";
  18. echo "\n" . highlight_phrases($s, $phrases);
  19.  
Success #stdin #stdout 0.01s 82944KB
stdin
Standard input is empty
stdout
Array
(
    [0] => iphone 7 plus
    [1] => iphone 7
)

/iphone 7 plus|iphone 7/i
This is some text about the <strong>iPhone 7</strong> and this i really a nice peace of engineering. We are now talking about the <strong>iPhone 7 Plus</strong>, which is very big!