4

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;

3 Answers 3

7

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'
Sign up to request clarification or add additional context in comments.

2 Comments

I can't get strpos( $inString , $inArray ) to work. The second parameter can't be an array in strpos. Have you really tested this?
Hi Olaf, Thanks for the comment. I can't remember what testing I did, as this answer was submitted over 2 years ago. But, I have adjusted the code so that it should now iterate through the array and perform the expected checks.
3

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

1 Comment

clean and simple. Exactly what I needed.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.