user765368
user765368

Reputation: 20356

multiple characters replacements in string php

Let's say that I have the following string:

$string = 'xxyyzz';

And then I have a substitution array like this:

$subs = ['xy'];

Meaning that every x should be replaced by y in my string and every y should be replaced by x. Let's say that my substitution array can only contain pairs of characters to be replaced in my $string.

How would I go about doing this?

I tried using str_replace the following way but that doesn't work:

foreach ($subs as $sub) {
    $sub_arr = str_split($sub);
    $reversed_sub_arr = array_reverse($sub_arr);

    $output = str_replace($sub_arr, $reversed_sub_arr, str_split($string));
}

$output = implode('', $output);

But the output gives me xxxxzz

The output should be yyxxzz

Thanks for any help

Upvotes: -1

Views: 87

Answers (2)

Bhaskar Jain
Bhaskar Jain

Reputation: 1691

Extending @Orgil answer if two items in $subs array like $subs = ['xy', 'dz']

$string = $output = 'xxyyzz';
$subs = ['xy', 'dz'];
foreach ($subs as $sub) {
    $sub_arr = str_split($sub);

    $output = strtr($output, array($sub_arr[0]=>$sub_arr[1], $sub_arr[1]=>$sub_arr[0]));

}
echo $output;

Demo

Upvotes: 1

Orgil
Orgil

Reputation: 251

This working for your case

  $string = 'xxyyzz';
$subs = ['xy'];
foreach ($subs as $sub) {
    $sub_arr = str_split($sub);

    $output = strtr($string, array($sub_arr[0]=>$sub_arr[1], $sub_arr[1]=>$sub_arr[0]));

}
echo $output; //yyxxzz

Upvotes: 2

Related Questions