You can use array_filter
to filter out any values of the array which are not a substring of $string
. Note I have used stripos
for a case-insensitive search, if you want the search to be case-sensitive just use strpos
instead.
$array = array('pro', 'gram', 'merit', 'program', 'it', 'programmer');
$string = "programit";
print_r(array_filter($array, function ($v) use($string) { return stripos($string, $v) !== false; }));
Output:
array
(
[0] => pro
[1] => gram
[3] => program
[4] => it
)
Update
Here is a recursive function which gives the same result.
function find_words($string, $array) {
if (count($array) == 0) return $array;
if (stripos($string, $array[0]) !== false)
return array_merge(array($array[0]), find_words($string, array_slice($array, 1)));
else
return find_words($string, array_slice($array, 1));
}
Demo of both methods on rextester