3v4l.org

run code in 300+ PHP versions simultaneously
<?php // all keys must be lowercase $keywords_external_path = array( "sweet potato" => "food/sweet-potato", "potato salads" => "food/potato-salads", "potato" => "food/potato", ); $data = array( 'post_content' => 'Sweet potato some text then potato then more text and then potato salads' ); $base = 'http://domain.com/'; // only if this is useful $keywords_external = array_keys($keywords_external_path); krsort($keywords_external); // to quickly discards useless position (if you have many keywords): you can also do the same with the second letter $keywords_first_letter = implode('', array_unique(array_reduce($keywords_external, function ($c, $i) { $c[]=$i[0]; return $c; }, []))); $pattern = '~\b(?=['. $keywords_first_letter . '])(?:' . implode('|', $keywords_external) . ')\b~i'; $result = preg_replace_callback($pattern, function ($m) use ($keywords_external_path, $base) { return '<a href="' . $base . $keywords_external_path . '">' . $m[0] . '</a>'; }, $data['post_content']); echo $result;
Output for 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
Warning: Array to string conversion in /in/Ye8ec on line 25 Warning: Array to string conversion in /in/Ye8ec on line 25 Warning: Array to string conversion in /in/Ye8ec on line 25 <a href="http://domain.com/Array">Sweet potato</a> some text then <a href="http://domain.com/Array">potato</a> then more text and then <a href="http://domain.com/Array">potato</a> salads
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Warning: Array to string conversion in /in/Ye8ec on line 25 Warning: Array to string conversion in /in/Ye8ec on line 25 Warning: Array to string conversion in /in/Ye8ec on line 25 <a href="http://domain.com/Array">Sweet potato</a> some text then <a href="http://domain.com/Array">potato</a> then more text and then <a href="http://domain.com/Array">potato</a> salads
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.2.5 - 7.2.33, 7.3.0 - 7.3.31, 7.4.0 - 7.4.25, 7.4.27 - 7.4.33
Notice: Array to string conversion in /in/Ye8ec on line 25 Notice: Array to string conversion in /in/Ye8ec on line 25 Notice: Array to string conversion in /in/Ye8ec on line 25 <a href="http://domain.com/Array">Sweet potato</a> some text then <a href="http://domain.com/Array">potato</a> then more text and then <a href="http://domain.com/Array">potato</a> salads
Output for 7.3.32 - 7.3.33, 7.4.26
<a href="http://domain.com/Array">Sweet potato</a> some text then <a href="http://domain.com/Array">potato</a> then more text and then <a href="http://domain.com/Array">potato</a> salads

preferences:
192.98 ms | 402 KiB | 202 Q