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;
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.5 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
<a href='helloworld-URL'>hello world</a>

preferences:
106.16 ms | 1463 KiB | 4 Q