如何在字符串内容"/"
时删除第一个模式匹配$a = "abc/def";
$b = "abc/def/ghi/abc/def";
$result = "/ghi/abc/def"; when replace with "abc/def" only look for the fist match
I try this but is not work.
$x = preg_replace('/'.$a.'/', '', $b, 1);
您必须记住,preg_replace的第一个参数是RegEx模式,因此您不能将任何字符串传递给它。
首先需要用preg_quote
函数转义所有regex字符试题:
$a = "abc/def";
$b = "abc/def/ghi/abc/def";
$pattern = preg_quote($a, '/'); // second argument allows us to escape delimiter chars, too
$x = preg_replace("/$pattern/", '', $b, 1);