如何在不使用str_replace函数的情况下使用数组来创建字符串替换函数?

时间:2017-05-18 11:34:48

标签: php arrays string replace

例如

$string = "Hello world.";

“lo”将替换为“aa”,“ld”将替换为“bb”。 输出将是

$string = "Helaa worbb";

2 个答案:

答案 0 :(得分:2)

这应该有效 -

$string = "Hello world.";
// pairs to replace
$replace_pairs = array("lo" => 'aa', 'ld' => 'bb');
// loop through pairs
foreach($replace_pairs as $replace => $new)
{
    // if present
    if(strpos($string, $replace)) {
        // explode the string with the key to replace and implode with new key
        $string = implode($new, explode($replace, $string));
    }
}

echo $string;

Demo

答案 1 :(得分:1)

这就是我提出的,你可以优化这段代码。

// assuming only 2 characters find and replace
$string = "Hello world.";
$aa = str_split($string); //converts string into array
$rp1 = 'aa'; //replace string 1
$rp2 = 'bb'; //replace string 2
$f1 = 'lo'; //find string 1
$f2 = 'ld'; // find string 2
function replaceChar($k1, $k2, $findStr, $replaceStr, $arr){
    $str = $arr[$k1].$arr[$k2];
    if($str == $findStr){
        $ra = str_split($replaceStr);
        $arr[$k1] = $ra[0];
        $arr[$k2] = $ra[1];
    }
    return $arr;
}
for($i=0; $i < count($aa)-1; $i++){
    $k1 = $i;
    $k2 = $i+1;
    $aa = replaceChar($k1, $k2, $f1, $rp1, $aa); //for replace first match string
    $aa = replaceChar($k1, $k2, $f2, $rp2, $aa); // for replace second match string 
}

echo implode('', $aa);

Demo