简体   繁体   中英

Compare string against array of strings in PHP?

I have a string like abcdefg123hijklm . I also have an array which contains several strings. Now I want to check my abcdefg123hijklm and see if the 123 from abcdefg123hijklm is in the array. How can I do that? I guess in_array() wont work?

Thanks?

So you want to check if any substring of that particular string (lets call it $searchstring ) is in the array? If so you will need to iterate over the array and check for the substring:

foreach($array as $string)
{
  if(strpos($searchstring, $string) !== false) 
  {
    echo 'yes its in here';
    break;
  }
}

See: http://php.net/manual/en/function.strpos.php

If you want to check if a particular part of the String is in the array you will need to use substr() to separate that part of the string and then use in_array() to find it.

http://php.net/manual/en/function.substr.php

Another option would be to use regular expressions and implode, like so:

if (preg_match('/'.implode('|', $array).'/', $searchstring, $matches))
    echo("Yes, the string '{$matches[0]}' was found in the search string.");
else
    echo("None of the strings in the array were found in the search string.");

It's a bit less code, and I would expect it to be more efficient for large search strings or arrays, since the search string will only have to be parsed once, rather than once for every element of the array. (Although you do add the overhead of the implode.)

The one downside is that it doesn't return the array index of the matching string, so the loop might be a better option if you need that. However, you could also find it with the code above followed by

$match_index = array_search($matches[0], $array);

Edit: Note that this assumes you know your strings aren't going to contain regular expression special characters. For purely alphanumeric strings like your examples that will be true, but if you're going to have more complex strings you would have to escape them first. In that case the other solution using a loop would probably be simpler.

You can do it reversely. Assume your string is $string and array is $array.

foreach ($array as $value)
{
    // strpos can return 0 as a first matched position, 0 == false but !== false
    if (strpos($string, $value) !== false)
    {
        echo 'Matched value is ' . $value;
    }  
} 

Use this to get your numbers

$re = "/(\d+)/";
$str = "abcdefg123hijklm";

preg_match($re, $str, $matches);

and ( 123 can be $matches[1] from above ):

   preg_grep('/123/', $array);

http://www.php.net/manual/en/function.preg-grep.php

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