开发者

Recursive PHP Function to Replace Characters

I'm trying to develope a recursive function I can use to strip a string of instances of multiple values.

This is what I have so far:

开发者_C百科
$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, $replace, $string);
            
            stripall($values, $replace, $string);
        }
    }
    
    return $string;
}

Here the $words string is getting stripped of all instances of two underscores (__) or a quote ("). Or at least in theory...

The target return value being:

one_two_three

However, what I am getting is "one_two___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, $replace, $string);
            stripall($values, $replace, $string);
        }
    }
    return $string;
}

Changed the IF to While and first remove " and then check for __


I'm kind of confused on your expected output:

one_two_three

Assuming your string:

$words = 'one__two_"__three';

And your rules:

Here the $words string is getting stripped of all instances of two underscores (__) or a quote (")

We would strip the string like this:

$words = 'one[__]two_["][__]three';

So your expected output should be:

onetwo_three

Which by using the array form of str_replace:

$words = 'one__two_"__three';
echo str_replace(array('"', "__"), "", $words) . "\n";

I get exactly that output:

$ php test.php
onetwo_three


I don't think anyone could possibly convince me to use a loop or non-regex approach for this one. If anyone would not use regex, I would assume that they simply don't understand the power and utility of performing replacements on varying character sequences.

The pattern merely sweeps through the input string(s) and replaces all sequences of one or more underscores and/or double quotes.

The only unnecessary side effect of this technique (but it doesn't negatively affect the outcome) is that it will needlessly replace a single underscore with a single underscore. Ideally patterns should not be designed to do needless matches/replacements, but in this case it spare the requirement to make a second sweep through the string(s) to clean up any newly generated consecutive underscores.

This perfectly tidies up your text with just one function call -- this is exactly why regex exists.

Code: (Demo)

$strings = [
    'one"two_"_"_three',
    'one__two_"__three',
    'one__two_"__""____"three',
    'one__two___"""""""______three',
];

var_export(
    preg_replace('~["_]+~', '_', $strings)
);

Output:

array (
  0 => 'one_two_three',
  1 => 'one_two_three',
  2 => 'one_two_three',
  3 => 'one_two_three',
)


Would you like to try mine?

//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), array_values($replacement), $key);
            }
            $newArr[$replacedKey] = strReplaceArrayRecursive($replacement, $value, $isReplaceKey);
        }
        return $newArr;
    }
}


This function is entirely unnecessary. str_replace already does the same thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜