preg_replace: 未知修饰符

5
假设 $body 等于:
something 
that 
does 
not 
interest 
me 
<!-- start -->
some
html
code
<!-- end -->
something
that
does
not
interest
me

如果我使用

$body=preg_replace("(.*)<!-- start -->(.*)<!-- end -->(.*)","$2",$body);

我得到的结果是:

警告:preg_replace() [function.preg-replace]:未知修饰符'<'

我该如何纠正?

3
使用 strpos 获取 start 的位置和 end 的位置可能更容易,然后使用 substr 只获取这些位置之间的部分。 - Gumbo
1
可能是重复的问题,与 警告:preg_replace():未知修饰符']' 相同(原因相同,缺少正则表达式定界符)。 - Peter Mortensen
2个回答

16

preg模式需要一对字符来标识模式本身。在这里,您的模式被包含在第一对括号中,其余内容则位于括号外。

尝试这样:

$body=preg_replace("/(.*)<!-- start -->(.*)<!-- end -->(.*)/","$2",$body);

这只涉及到语法,对于看起来可疑的模式本身没有任何保证。

假设你的示例文本如下:

preg_match('#<!-- start -->(.*?)<!-- end -->#s', $text, $match);
$inner_text = trim($match[1]);

将“ ”替换为“$2”可以解决这个问题。但我有一个问题,使用$2会影响到其他区域吗? - Vinith

2

试试这个:

$body = preg_replace("/(.*)<!-- start -->(.*)<!-- end -->(.*)/","$2",$body);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接