Skip to content
Advertisement

Remove Same Character once from two different string

I need help in PHP Script.

I have two strings.

$string1 = "asdfgf";
$string2 = "asdfgasdg";

After removing the same character from both string once,

$string1 = "f";
$string2 = "asdg";

Another Two Strings example

$string1 = "sthnfr";
$string2 = "iserr";

Output

$string1 = "thnf"; // s and r removed
$string2 = "ier"; // s and r removed

I tried str_replace which replace all the all the characters. Thanks for your helps

Advertisement

Answer

$string2 = "sthnfr";
$string1 = "iserr";

for($i = 0; $i < strlen($string1); )
{
    if(($pos = strpos($string2, $string1[$i])) !== false)
    {
        $string1 = substr($string1, 0, $i) . substr($string1, $i + 1);
        $string2 = substr($string2, 0, $pos) . substr($string2, $pos + 1);
        continue;
    }
    $i++;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement