3v4l.org

run code in 300+ PHP versions simultaneously
<?php $text="hello world"; $searches= array(); $searches = array( array("text" => "hello", "url" => "hello-URL"), array("text" => "world", "url" => "world-URL"), array("text" => "hello world", "url" => "helloworld-URL") ); usort($searches, function($a, $b) { return strlen($b['text']) - strlen($a['text']); }); $pat = '~(?<!\w)(?:' . implode("|", array_map(function($x) { return preg_quote($x['text'], '~'); }, $searches) ) . ')(?!\w)~i'; // echo "$pat\n"; // => ~(?<!\w)(?:hello world|hello|world)(?!\w)~i $keys = array(); $vals = array(); foreach($searches as $search) { $keys[] = $search['text']; $vals[] = $search['url']; } $tmparr = array_combine($keys, $vals); $text = preg_replace_callback($pat, function($m) use ($tmparr) { return "<a href='" . $tmparr[$m[0]] . "'>" . $m[0] . "</a>"; }, $text); echo $text;

preferences:
118.54 ms | 1467 KiB | 5 Q