3v4l.org

run code in 300+ PHP versions simultaneously
<?php $bads = array('+11','- 68','[img','$cool', '# hash'); // disallowed full 'words'; if one of them appears in string, the function should return true $s= 'This is test to show if or $cool works but it does not'; //another example to test: $s= 'This - 68 is # hash not'; if(contains($s,$bads)) { echo 'Contains! '; } #### FUNCTION ### function contains($str, $bads) { //var_dump($bads); $b = "/"; foreach($bads as $a) { if(substr($a,0,1) == "$"){ $b .= preg_quote($a,'/'). "|"; }else{ $b .= "\b" . preg_quote($a,'/'). "\b|"; } } $b = substr($b, 0,-1) ."/"; echo $b; if(preg_match($b,$str, $m)){ var_dump($m); return true; } return false; }
Output for 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
/\b\+11\b|\b\- 68\b|\b\[img\b|\$cool|\b\# hash\b/array(1) { [0]=> string(5) "$cool" } Contains!
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33
/\b\+11\b|\b\- 68\b|\b\[img\b|\$cool|\b# hash\b/array(1) { [0]=> string(5) "$cool" } Contains!

preferences:
155.21 ms | 407 KiB | 5 Q