Search code examples
phpvalidationcharactermatchingwhitelist

Check if a string is solely composed of characters found in another string


Considering sample data such as:

$str1 = "apple";
$str2 = "pal";

I want to return a true response only if all the characters [alphabetical characters] of the $str2 are also present in $str1, otherwise false.

Since all letters p, a, and l all exist in $str1, then result should be true.

If $str2 was pole, then the p, l, and e would be found, but the o would not. This scenario should return false.

My pseudo code is:

if (str2 is present in str1){
    // true;
    // since all characters of str2 are also in str1, so it should return true.
} else{
    // false;
}

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.