2010-03-26 91 views
6

讓我們假設$身體等於的preg_replace:未知的修飾

something 
that 
does 
not 
interest 
me 
<!-- start --> 
some 
html 
code 
<!-- end --> 
something 
that 
does 
not 
interest 
me 

如果我使用

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

我獲得:

Warning: preg_replace() [function.preg-replace]: Unknown modifier '<' 

如何有我糾正?

+3

它可能是更容易得到的* *開始的位置和結束* *在'strpos'的位置,然後讓只是這些位置與'substr'之間的部分。 – Gumbo 2010-03-26 17:48:05

回答

17

preg圖案需要一對限定所述圖案本身的字符。這裏你的模式被包含在第一對括號中,而其他所有內容都在外面。

試試這個:

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

這只是有關語法上看起來可疑圖案自身難保。

編輯:

假設在你的榜樣文字:

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

用「$ 2」代替「」解決了這個問題。仍然有一個問題,使用2美元會影響其他任何區域嗎? – Vinith 2014-02-11 13:58:59

3

嘗試這種情況:

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