I thought this would be a simple thing to do with a native php function but i've found a few different, all quite complicated, ways that people have tried to achieve it. What's the most efficient way of checking if a string contains one or more elements in an array? i.e, below - where $data['description'] is a string. Obv the in_array check below breaks because it expects param 2 to be an array
$keywords = array(
'bus',
'buses',
'train',
);
if (!in_array($keywords, $data['description']))
continue;
function arrayInString( $inArray , $inString , $inDelim=',' ){
$inStringAsArray = explode( $inDelim , $inString );
return ( count( array_intersect( $inArray , $inStringAsArray ) )>0 );
}
Example 1:
arrayInString( array( 'red' , 'blue' ) , 'red,white,orange' , ',' );
// Would return true
// When 'red,white,orange' are split by ',',
// the 'red' element matched the array
Example 2:
arrayInString( array( 'mouse' , 'cat' ) , 'mouse' );
// Would return true
// When 'mouse' is split by ',' (the default deliminator),
// the 'mouse' element matches the array which contains only 'mouse'
function arrayInString( $inArray , $inString ){
if( is_array( $inArray ) ){
foreach( $inArray as $e ){
if( strpos( $inString , $e )!==false )
return true;
}
return false;
}else{
return ( strpos( $inString , $inArray )!==false );
}
}
Example 1:
arrayInString( array( 'apple' , 'banana' ) , 'I ate an apple' );
// Would return true
// As 'I ate an apple' contains 'apple'
Example 2:
arrayInString( array( 'car' , 'bus' ) , 'I was busy' );
// Would return true
// As 'bus' is present in the string, even though it is part of 'busy'
You can do this using regular expressions -
if( !preg_match( '/(\b' . implode( '\b|\b', $keywords ) . '\b)/i', $data['description'] )) continue;
the result regexp will be /(\bbus\b|\bbuses\b|\btrain\b)/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With