8

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.

2
  • 1
    Use str_split() to split them into arrays, then array_intersect() to identify the matching characters Commented Nov 29, 2014 at 12:00
  • @MarkBaker Sounds great, can you show in an answer please. Commented Nov 29, 2014 at 12:01

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Also strcspn which will essentially return string position of the first illegal character or false if none exist. Instead of the initial string part up to the first illegal character that is.
2

+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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.