简体   繁体   中英

check a string contains any word from array

i have a set of predefined array contains strings and words.I am trying to check whether my string contains at least one word from that array.

$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code testy';//code is already in that array

i tried many ways,but not correct solution

first method

$i = count(array_intersect($array, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $string))));
echo ($i) ? "found ($i)" : "not found";

second method

if (stripos(json_encode($array),$string) !== false) { echo "found";}
else{ echo "not found";} 

I suppose you are looking for a match which is any of the words.

$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code|testy';

foreach ($array as $item ) {
    
    if(preg_match("/\b{$string}\b/i", $item)) {
        var_dump( $item );
    }
}

You have to iterate over the array and test each one of the cases separately, first 'code', then 'testy', or whatever you want. If you json_encode, even if you trim both of strings to do this comparaison, the return will be not found.

But in the first string if you had like this

$array = array("PHP code testy Sandbox Online","abcd","defg" );
$string = 'code testy';//code is already in that array

you will get surely a "found" as return.

if (stripos(trim(json_encode($array)),trim($string)) !== false) { echo "found";}
else{ echo "not found";}

You could use explode() to get an array from the strings and then go through each of them.

$array = array("PHP code tester Sandbox Online","abcd","defg" );
$string = 'code testy';

foreach(explode(' ', $string) as $key => $value) {
    foreach($array as $arrKey => $arrVal) {
        foreach(explode(' ', $arrVal) as $key => $str) {
            if ($value == $str) {
                echo $str . ' is in array';
            }
        }
    }
}

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