Search code examples
phpsearchstrposstring-searchapproximate

php strpos and approximate match with 1 character difference


I searched the system but couldn't find any help I could understand on this, so here goes...

I need to find an approximate match for a string in php.

Essentially I'm checking that all the $names are in the $cv string and if not it sets a flag to true.

foreach( $names as $name ) {
    if ( strrpos( $cv, $name ) === false ) {
        $nonameincv = true;
    }
}

It works fine. However, I had a case of $cv = "marie_claire" and a $name = "clare" which set the flag (of course) but which I'd have liked for strpos to have "found" as it were.

Is it possible to do an approximate match so that if a string has 1 extra letter anywhere in it, it would match? For example so that:

$name = "clare" is found in $cv = "marie_claire"

$name = "caire" is found in $cv = "marie_claire"

$name = "laire" is found in $cv = "marie_claire"

and so on...


Solution

  • Note: This will work perfectly fine when there is difference of 1 character, as stated in question above.

    Try this code snippet here

    <?php
    ini_set('display_errors', 1);
    $stringToSearch="mare";
    $wholeString = "marie_claire";
    
    $wholeStringArray=  str_split($wholeString);
    for($x=0;$x<strlen($wholeString);$x++)
    {
        $tempArray=$wholeStringArray;
        unset($tempArray[$x]);
        if(strpos(implode("", $tempArray),  $stringToSearch)!==false)
        {
            echo "Found: $stringToSearch in ".implode("", $wholeStringArray);
            break;
        }
    }