php如何用preg_replace动态替换字符串范围?

我想使用 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);


墨色风雨
浏览 104回答 2
2回答

HUWWW

有preg_replace_callback可用的,这通常是进行任何动态替换的最佳方法。将它与类似的模式一起使用,([DM])\d\d(?!\d)并根据捕获替换。$new_str = preg_replace_callback('/([DM])\d\d(?!\d)/', function($m) {&nbsp; return $m[1]=="D" ? "" : '<br/>';}, $str1);在 tio.run 上查看这个 PHP 演示&nbsp; (前瞻用于不匹配例如D001)使用回调的好处是,您在处理捕获的值时范围很广。单独的正则表达式不适合匹配数字范围,但可以很容易地被任何函数进一步检查。无论如何,您的示例任务也可以通过preg_replace数组来完成。$new_str = preg_replace(['/D\d\d(?!\d)/', '/M\d\d(?!\d)/'], ["", '<br/>'], $str1);

POPMUISE

您可以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/>"]
打开App,查看更多内容
随时随地看视频慕课网APP