Search code examples
phpregexstringsubstringstrpos

similar substring in other string PHP


How to check substrings in PHP by prefix or postfix. For example, I have the search string named as $to_search as follows:

$to_search = "abcdef"

And three cases to check the if that is the substring in $to_search as follows:

$cases = ["abc def", "def", "deff", ... Other values ...];

Now I have to detect the first three cases using substr() function. How can I detect the "abc def", "def", "deff" as substring of "abcdef" in PHP.


Solution

  • To find any of the cases that either begin with or end with either the beginning or ending of the search string, I don't know of another way to do it than to just step through all of the possible beginning and ending combinations and check them. There's probably a better way to do this, but this should do it.

    $to_search = "abcdef";
    $cases = ["abc def", "def", "deff", "otherabc", "noabcmatch", "nodefmatch"];
    
    $matches = array();
    $len = strlen($to_search);
    for ($i=1; $i <= $len; $i++) {
        // get the beginning and end of the search string of length $i
        $pre_post = array();
        $pre_post[] = substr($to_search, 0, $i);
        $pre_post[] = substr($to_search, -$i);
    
        foreach ($cases as $case) {
            // get the beginning and end of each case of length $i
            $pre = substr($case, 0, $i);
            $post = substr($case, -$i);
    
            // check if any of them match
            if (in_array($pre, $pre_post) || in_array($post, $pre_post)) {
                // using the case as the array key for $matches will keep it distinct
                $matches[$case] = true;
            }
        }
    }
    // use array_keys() to get the keys back to values
    var_dump(array_keys($matches));