简体   繁体   中英

replacing characters in a string in php

I couldn't think of a good question title but my problem is that I have to replace certain characters in a string but don't want to replace characters that are already replaced, for instance,

 $s = "abcabacababbccc";

if I have to replace abc with bcc and bc with aa then I should get

 $s = "bccabacababaac";

But I'm getting a different string as output because then the other replacing function is called it starts searching string from the start and I ought to avoid it. I have written this code, if anyone could help me sort it out. thanks

$_set = "abcacbabccbacab";
    $_set = InvokeRule1($_set);
    $_set = InvokeRule2($_set);
    $_set = InvokeRule3($_set);

function InvokeRule1($set)
{
    $check = false;
        $set = str_replace("abc", "bcc", $set);
        $check = true;

    return $set;
}

 function InvokeRule2($set)
{
    $check = false;
        $set = str_replace("bc", "aa", $set);
        $check = true;
    return $set;
}

well credit to Mark Baker, but no one else seems keen on actually posting an "answer" so:

$trans = array("abc" => "bcc", "bc" => "aa");
echo strtr("abcabacababbccc", $trans); //=bccabacababaacc

Try something like this:

$phrase  = "abcabacababbccc";
$newPhrase = str_replace("abc", "BCC", $phrase);
$newPhrase2 = str_replace("bc", "AA", $newPhrase);
echo strtolower($newPhrase2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM