我想使用preg_replace动态替换字符范围。例如D01至D99我想将此字符串范围替换为空白,而M01至M99希望将其替换为<br/>
标签。我正在尝试使用静态值数组替换它。这是我的代码。
$str1 = "This is mystrD01 and this is D03just for testingD02.M01Loream ipsum text1M02loream ipsum text2";
$arr1 = array("D01","D02","D03","D04","M01","M02","M03");
$replaceArr = array("","","","","<br/>","<br/>","<br/>");
echo str_replace($str_arr1,$replace_arr2,$str2);
答案 0 :(得分:2)
有preg_replace_callback
可用,这通常是进行任何动态替换的最佳方法。将其与([DM])\d\d(?!\d)
之类的模式一起使用,并根据capture进行替换。
$new_str = preg_replace_callback('/([DM])\d\d(?!\d)/', function($m) {
return $m[1]=="D" ? "" : '<br/>';
}, $str1);
See this PHP demo at tio.run(lookahead用于不匹配,例如D001
)
使用回调的优点是,您可以处理捕获的值。单独的正则表达式不能很好地匹配数字范围,但是任何函数都可以轻松地对其进行进一步检查。
无论如何,您的示例任务也可以由preg_replace
与数组一起完成。
$new_str = preg_replace(['/D\d\d(?!\d)/', '/M\d\d(?!\d)/'], ["", '<br/>'], $str1);
答案 1 :(得分:1)
您可以在具有正则表达式匹配项的数组上使用preg_replace
。
D\d*
将匹配“ D”,然后匹配任意数字。
$arr1 = array("D01","D02","D03","D04","M01","M02","M03");
$arr1 = preg_replace("/D\d*/", '', $arr1);
$arr1 = preg_replace("/M\d*/", '<br />', $arr1);
输出-
["","","","","<br/>","<br/>","<br/>"]