Reputation: 393
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
Upvotes: 0
Views: 621
Reputation: 47904
Iterate each character in the first string (use mb_str_split()
from PHP7.4 if you are processing strings with multibyte characters).
Replace the first occurrence of the isolated character in the second string with an empty string; limit the replacements to 1; and temporarily store the the success of the replacement in $count
. preg_quote()
is used to stabilize the pattern and protect it from characters with special meaning to the regex engine. Again, if multibyte characters are possible, add the u
pattern modifier after the last /
in the first parameter of preg_replace()
.
If $count
is 0
, then there was no match and the isolated character should be appended to the iteratively rebuilt $newA
string.
Using this technique, the first string only grows larger as not-found characters are encountered and the second string only gets smaller as found characters are encountered. In other words, for every character iterated, either the seconds string loses a character or the new first string gains a character.
This technique is built to sanitize shared characters in both strings regardless of the order/position of the characters in the strings. It is also very easy to extend to cover multibyte scenarios.
Function: (Demo)
function removeSharedCharacters(string $a, string $b): array {
$newA = '';
foreach (str_split($a) as $char) {
$b = preg_replace('/' . preg_quote($char, '/') . '/', '', $b, 1, $count);
if (!$count) {
$newA .= $char;
}
}
return [$newA, $b];
}
Test cases and function call:
$tests = [
["asdfgf", "asdfgasdg"],
["sthnfr", "iserr"],
["acegik", "jihgfedcba"]
];
foreach ($tests as $pair) {
var_export(removeSharedCharacters(...$pair));
echo "\n---\n";
}
Output:
array (
0 => 'f',
1 => 'asdg',
)
---
array (
0 => 'thnf',
1 => 'ier',
)
---
array (
0 => 'k',
1 => 'jhfdb',
)
---
Upvotes: 0
Reputation:
$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++;
}
Upvotes: 1