Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array element exists in string

Tags:

arrays

php

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;
like image 628
user1153594 Avatar asked Dec 21 '22 23:12

user1153594


2 Answers

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'
like image 143
Luke Stevenson Avatar answered Jan 03 '23 03:01

Luke Stevenson


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

like image 32
SergeS Avatar answered Jan 03 '23 02:01

SergeS