I couldn’t find an out-of-the-box PHP function to do a partial string search in an array of strings. So I had to write a simple helper function using strpos for a WordPress project, I am working on.
Partial string search in an array using strpos
Here is the snippet in case you need it.
/**
* Helper function to do a partial search for string inside array.
*
* @param array $array Array of strings.
* @param string $keyword Keyword to search.
*
* @return array
*/
function array_partial_search( $array, $keyword ) {
$found = [];
// Loop through each item and check for a match.
foreach ( $array as $string ) {
// If found somewhere inside the string, add.
if ( strpos( $string, $keyword ) !== false ) {
$found[] = $string;
}
}
return $found;
}
// Simple list of fruits.
$fruits = [ 'apple', 'grapes', 'orange', 'pineapple' ];
// Result - [ 'apple', 'grapes', 'pineapple' ];
$found = array_partial_search( $fruits, 'ap' );
Let me know in comments if you think there is a better alternative available.


if (strpos((string) $string, $keyword) === FALSE) {
}
preg_grep() 😀