php - Check if a string is solely composed of characters found in another string
<{-cod{-code-15}-6}>Consid{-code-15}ring s{-cod{-code-15}-7}m{-cod{-code-15}-6}{-cod{-code-15}-8}{-code-15} d{-cod{-code-15}-7}t{-cod{-code-15}-7} such {-cod{-code-15}-7}s:{-cod{-code-15}-6}>
<{-cod{-code-15}-6}r{-code-15}>
Answer
Solution:
Use the first string (whitelist string) as the mask for trim()
. This will remove all matched characters from the second string. If there are any characters remaining after the trim, then false
.
since all characters of str2 are also in str1, so it should return true
Code: (Demo)
$str1 = "apple";
$str2 = "pal";
$str3 = "pole";
var_export(!strlen(trim($str2, $str1)));
echo "\n---\n";
var_export(!strlen(trim($str3, $str1)));
Output:
true
---
false
This answer is clean and direct because it does not need to generate temporary arrays for subsequent comparison. trim()
's character mask affords the same action that str_replace()
is famous for, but without needing to split the whitelist string into an array first. I don't know if ltrim()
or rtrim()
would be any faster (on a microscopic level) than trim()
, but any of these functions will deliver the same output.
p.s. If you are guaranteed to only be working with letters, then you can use a falsey check instead of strlen()
.
!trim($str2, $str1)
I say this because if you allowed numbers, then a trimmed string containing a zero would be considered falsey and return an incorrect result.
Answer
Solution:
You can use the array_intersect function after splitting each characters from a word using the str_split function as:
<?php
$a = "Apple";
$b = "pal";
$matched = !empty(array_intersect(str_split($b), str_split($a)));
array_intersect will return [ p, l ] ignoring 'A' due to case sensitive
echo $matched; // true
?>
In case if you want to match ignoring the case of the characters then you can first lowercase the word using the strtolower function: and then split as:
$a = "Apple";
$a = strtolower($a);
Answer
Solution:
You can use count_chars() to get array of present chars in each string and then compare those two arrays:
$s1 = 'apple';
$s2 = 'pal';
$c1 = count_chars($s1, 1);
$c2 = count_chars($s2, 1);
$ok = empty(array_diff_key($c2, $c1));
Source