3v4l.org

run code in 300+ PHP versions simultaneously
<?php $keywords = ["key1", "key2"]; $escaped = implode('|', array_map('preg_quote', $keywords)); $pattern = "/\b(?:" . $escaped . ")\b" . ":?(?:\h+|$)|\b(?!(?:" . $escaped . ")\b)[^\s:]+:/"; $strings = [ "aaa bbb key1 ccc", "aaa bbb key1:xxx key2:", "aaa bbb key1: xxx ccc", "aaa bbb key1 :xxx ccc", "aaa bbb xxx:yyy zzz", "aaa bbb ccc", "aaa bbb key1:aaa ccc ddd", "aaa bbb key2:aaa key1:bbb", "aaa bbb aakey1", "aaa bbb key1aa", "aaa bbb key1aa" ]; foreach ($strings as $s) { preg_match_all($pattern, $s, $matches); if (count($matches[0]) > 0) { foreach ($matches[0] as $m) { echo "Invalid string -->'$m' is invalid format, please check it again..." . PHP_EOL; } } else { echo "Valid string --> '$s'" . PHP_EOL; } }
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
Invalid string -->'key1 ' is invalid format, please check it again... Invalid string -->'key2:' is invalid format, please check it again... Invalid string -->'key1: ' is invalid format, please check it again... Invalid string -->'key1 ' is invalid format, please check it again... Invalid string -->'xxx:' is invalid format, please check it again... Valid string --> 'aaa bbb ccc' Valid string --> 'aaa bbb key1:aaa ccc ddd' Valid string --> 'aaa bbb key2:aaa key1:bbb' Valid string --> 'aaa bbb aakey1' Valid string --> 'aaa bbb key1aa' Valid string --> 'aaa bbb key1aa'

preferences:
158.1 ms | 403 KiB | 123 Q