简体   繁体   中英

Check if array element exists in string

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? ie, 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;

Assuming that the String is a collapsed/delimited list of values

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'

Assuming that the String is plain text, and you are simply looking for instances of the specified words inside it

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)/

Asssuming whole words and phrases are being searched for

This function will find a (case-insensitive) phrase from an array of phrases within a string. If found, the phrase is reurned and $position returns its index within the string. If not found, it returns FALSE.

function findStringFromArray($phrases, $string, &$position) {
    // Reverse sort phrases according to length.
    // This ensures that 'taxi' isn't found when 'taxi cab' exists in the string.
    usort($phrases, create_function('$a,$b',
                                    '$diff=strlen($b)-strlen($a);
                                     return $diff<0?-1:($diff>0?1:0);'));

    // Pad-out the string and convert it to lower-case
    $string = ' '.strtolower($string).' ';

    // Find the phrase
    foreach ($phrases as $key => $value) {
        if (($position = strpos($string, ' '.strtolower($value).' ')) !== FALSE) {
            return $phrases[$key];
        }
    }

    // Not found
    return FALSE;
}

To test the function,

$wordsAndPhrases = array('taxi', 'bus', 'taxi cab', 'truck', 'coach');
$srch = "The taxi cab was waiting";

if (($found = findStringFromArray($wordsAndPhrases, $srch, $pos)) !== FALSE) {
    echo "'$found' was found in '$srch' at string position $pos.";
}
else {
    echo "None of the search phrases were found in '$srch'.";
}

As a matter of interest, the function demonstrates a technique for finding whole words and phrases, so that "bus" is found but not "abuse". Just surround both your haystack and your needle with space:

$pos = strpos(" $haystack ", " $needle ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM