preg_replace第一个匹配模式包括斜杠

时间:2011-07-15 02:40:54

标签: php regex

如何在字符串内容“/”

时删除第一个模式匹配
$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);

1 个答案:

答案 0 :(得分:2)

你必须记住preg_replace的第一个参数是一个RegEx模式,所以你不能只传递任何字符串。

首先,您需要使用函数preg_quote

转义所有正则表达式字符

尝试:

$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);