At the risk of also incurring hefty downvotes one possible method, if I understood correctly, would be to use a regExp
and create a pattern using all the possible words from the $findme
array.
$str='my fictional favourite food is Jellof Rice with salted water but not too much sugar and some rice';
#$str='banana apple mango';
$words=array( 'food', 'water', 'salt' );
function findmatches( $str=false, $search=array()){
if( !empty( $str ) && !empty( $search ) ){
# modify source array by quoting words if they require
array_walk( $search, function( &$item ){
$item=preg_quote( $item, '@' );
});
# generate the simple pattern by imploding all the words
$pttn=sprintf('@(\w%s)@',implode( '|', $search ) );
# try to capture all matches
preg_match_all( $pttn, $str, $matches, PREG_OFFSET_CAPTURE );
# return a suitable result - the frst set of matches or false if not found
return !empty( array_filter( $matches ) ) ? $matches[0] : false;
}
return false;
}
function showresults( $arr ){
# utility to display the results
if( !empty( $arr ) ){
foreach( $arr as $i => $v ){
printf('The word "%s" was found at position %s',$v[0],$v[1]);
}
}
}
$res=findmatches( $str, $words );
echo $res ? showresults($res) : 'Not found';
Which will output
The word "salt" was found at position 48
Array
(
[0] => salt
[1] => 48
)
The word "water" was found at position 55
Array
(
[0] => water
[1] => 55
)
Live example