user2039981
user2039981

Reputation:

PHP - Check if a string contains any of the chars in another string

How can I check if a string contains any of the chars in another string with PHP?

$a = "asd";
$b = "ds";
if (if_first_string_contains_any_of_the_chars_in_second_string($a, $b)) {
    echo "Yep!";
}

So in this case, it should echo, since ASD contains both a D and an S.

I want to do this without regexes.

Upvotes: 7

Views: 2790

Answers (4)

voodoo417
voodoo417

Reputation: 12111

+1 @hardik solanki. Also, you can use similar_text ( count/percent of matching chars in both strings).

$a = "asd";
$b = "ds";
if (similar_text($a, $b)) {
  echo "Yep!";
}

Note: function is case sensitive.

Upvotes: 1

Hardik Solanki
Hardik Solanki

Reputation: 3195

You can do it using

$a = "asd";
$b = "ds";
if (strpbrk($a, $b) !== FALSE)
    echo 'Found it';
else
    echo "nope!";

For more info check : http://php.net/manual/en/function.strpbrk.php

Second parameter is case sensitive.

Upvotes: 12

hoang hieu
hoang hieu

Reputation: 1

try to use strpos . Hope it helpful

Upvotes: 0

Amrinder Singh
Amrinder Singh

Reputation: 5532

you can use str_split function here, then just have a look at the given links: this might help you,

http://www.w3schools.com/php/showphp.asp?filename=demo_func_string_str_split http://www.w3schools.com/php/func_array_intersect.asp

Upvotes: 0

Related Questions