我正在尝试开发一个递归函数,可以用来剥离多个值的字符串实例。
这就是我目前所拥有的:
$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;
}
在这里,$words字符串去掉了两个下划线(__)或一个引号(quot;)的所有实例。或者至少在理论上。。。
目标返回值为:
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;
}
将IF更改为While并首先删除",然后检查__
我对您的预期输出有点困惑:
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
我认为没有人能说服我使用循环或非正则表达式的方法。如果有人不使用regex,我会认为他们根本不了解对不同的字符序列执行替换的功能和实用性。
该模式只扫描输入字符串,并替换一个或多个下划线和/或双引号的所有序列。
这种技术唯一不必要的副作用(但不会对结果产生负面影响)是,它将不必要地用单个下划线替换单个下划线。理想情况下,模式不应该被设计为进行不必要的匹配/替换,但在这种情况下,它不需要对字符串进行第二次扫描,以清除任何新生成的连续下划线。
这只需一个函数调用就可以完美地整理文本——这正是regex存在的原因。
代码:(演示)
$strings = [
'one"two_"_"_three',
'one__two_"__three',
'one__two_"__""____"three',
'one__two___"""""""______three',
];
var_export(
preg_replace('~["_]+~', '_', $strings)
);
输出:
array (
0 => 'one_two_three',
1 => 'one_two_three',
2 => 'one_two_three',
3 => 'one_two_three',
)
你想试试我的吗?
//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;
}
}
这个函数完全没有必要。str_replace
已经做了同样的事情。