Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search array of string in another string in PHP?

Tags:

arrays

string

php

Firstly, I want to inform that, what I need is the reverse of in_array PHP function.

I need to search all items of array in the string if any of them found, function will return true otherwise return false.

I need the fastest solution to this problem, off course this can be succeeded by iterating the array and using the strpos function.

Any suggestions are welcome.

Example Data:

$string = 'Alice goes to school every day';

$searchWords = array('basket','school','tree');

returns true

$string = 'Alice goes to school every day';

$searchWords = array('basket','cat','tree');

returns false

like image 302
Umut KIRGÖZ Avatar asked Jun 03 '11 14:06

Umut KIRGÖZ


People also ask

How can find string from another string in PHP?

Answer: Use the PHP strpos() Function The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .

How do you find if an array contains a specific string in PHP?

Use strpos() and json_encode() to Check if String Contains a Value From an Array in PHP. json_encode() is a built-in PHP function to convert the array into a JSON object, in simple words into a string. The above code converts the array into and string and checks if it contains a substring.

What is the use of strpos () function in PHP?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.


1 Answers

You should try with a preg_match:

if (preg_match('/' . implode('|', $searchWords) . '/', $string)) return true;

After some comments here a properly escaped solution:

function contains($string, Array $search, $caseInsensitive = false) {
    $exp = '/'
        . implode('|', array_map('preg_quote', $search))
        . ($caseInsensitive ? '/i' : '/');
    return preg_match($exp, $string) ? true : false;
}
like image 126
malko Avatar answered Nov 12 '22 09:11

malko