r/PHP • u/anthonybudd • Nov 17 '17
PHP Code Golf: Detect if string contains an element from array.
Throughout my 6+ year career I have had to write code for checking if one or more strings exist in another string. When doing this in the past, I have resorted to foreach loops. Today I discovered a way that looks ugly as hell but I prefer it to using a 3 or 4 line foreach loop. I'm really interested to know if anyone knows of any better solutions.
My solution 103 characters: https://gist.github.com/anthonybudd/9c32cc1698cb8b1d6144944a402e3c1c
<?php $array = ['quick', 'uick brown fo']; $string = 'the quick brown fox jumps over the lazy dog'; if(YOUR CODE HERE){ // The string contains an element in the array }
33
u/[deleted] Nov 17 '17
You just want a TRUE and FALSE?
5
u/JustSayNoToSlogans Nov 17 '17 edited Nov 17 '17
In 64 disgusting characters:
Removing $t=0; reduces it to 59, then it will still work but generates a NOTICE every time.
2
u/doubouil Nov 17 '17 edited Nov 17 '17
implode/explode might be my favorite functions.
Edit : $array was ['quick', 'fox'], so no longer valid
4
u/JustSayNoToSlogans Nov 17 '17 edited Nov 17 '17
A couple of ideas:
or
EDIT: strpos($string,$e) needs to be replaced with is_int(strpos($string,$e)), see reply below
2
u/gouchaoer Nov 19 '17
Ahocorasick keyword match a implementafion:https://github.com/imaben/php-akm/blob/master/README.md
1
u/opmrcrab Nov 21 '17
Just to be a jerk, since $arrays and $string are hard coded, I will say my answer is
Becuase it is :P
1
u/natowelch Nov 17 '17
if(preg_match('/'.join('|',$array).'/',$string))
This will work only if you can depend on your array values having no regex characters. Otherwise, you would need this:
if(preg_match('/'.join('|',array_filter($array,'preg_quote')).'/',$string))
1
u/chemisus Nov 17 '17
47 chars (of course won't work if the strings you're testing for are 0-n)
2
u/[deleted] Nov 17 '17
[removed] — view removed comment