递归PHP函数替换字符

问题描述

|| 嗨,我正在尝试开发一个递归函数,可以用来剥离多个值实例的字符串。 这是我到目前为止的内容
$words = \'one__two_\"__three\';

$words = stripall(array(\'__\',\'\"\'),\'_\',$words);

echo $words;

function stripall($values,$replace,$string) {

    foreach ($values as $value) {

        if (strpos($string,$value)) {

            $string = str_replace($value,$string);

            stripall($values,$string);
        }
    }

    return $string;
}
这里的$ words字符串被剥去了两个下划线(__)或引号(\“)的所有实例。或者至少在理论上…… 目标返回值为:
one_two_three
但是,我得到的是“ one_two___three” 有人可以帮忙吗?     

解决方法

        我对您的预期输出感到困惑:
one_two_three
假设您的字符串:
$words = \'one__two_\"__three\';
和你的规则:   在这里$ words字符串越来越   剥夺了两个的所有实例   下划线(__)或引号(\“) 我们将像这样剥离字符串:
$words = \'one[__]two_[\"][__]three\';
因此,您的预期输出应为:
onetwo_three
通过使用str_replace的数组形式:
$words = \'one__two_\"__three\';
echo str_replace(array(\'\"\',\"__\"),\"\",$words) . \"\\n\";
我确切地得到输出:
$ php test.php
onetwo_three
    ,        
$words = \'one__two_\"__three\';
$words = stripall(array(\'\"\',\'__\'),\'_\',$words);
echo $words;
function stripall($values,$replace,$string) {
    foreach ($values as $value) {
        while (strpos($string,$value)) {
            $string = str_replace($value,$string);
            stripall($values,$string);
        }
    }
    return $string;
}
将IF更改为While,然后先删除\“,然后检查__     ,        您想尝试我的吗?
//Example:
/*
    $data = strReplaceArrayRecursive(
        array(\'{name}\'=>\'Peter\',\'{profileImg}\'=>\'./PRF-AAD036-51dc30ddc4.jpg\'),array(
            \'title\'=>\'My name is {name}\',\'post\'=>array(
                \'author\' => \'{name}\',\'image\' => \'{profileImg}\',\'content\' => \'My post.\'
            )
        )
    );
    print_r($data);
//Expect:
Array
(
    [title] => My name is Peter
    [post] => Array
        (
            [author] => Peter
            [image] => ./PRF-AAD036-51dc30ddc4.jpg
            [content] => My post.
        )

)
*/
function strReplaceArrayRecursive($replacement=array(),$strArray=false,$isReplaceKey=false){
    if (!is_array($strArray)) {
        return str_replace(array_keys($replacement),array_values($replacement),$strArray);
    }
    else {
        $newArr = array();
        foreach ($strArray as $key=>$value) {
            $replacedKey = $key;
            if ($isReplaceKey) {
                $replacedKey = str_replace(array_keys($replacement),$key);
            }
            $newArr[$replacedKey] = strReplaceArrayRecursive($replacement,$value,$isReplaceKey);
        }
        return $newArr;
    }
}
    ,        完全不需要此功能。
str_replace
已经做了同样的事情。