2009-02-25 56 views
2

陷於PHP中的一個(相當簡單的)正則表達式問題。正則表達式基礎知識:在兩個常量之間抓取文本

文字的混亂是埋本節:

<tr> 
     <td id="descriptionArea"> 
      Customer request to remove "Intro - 01/13/09" video clip. 
      <br/> 
     </td> 
    </tr> 

我想無論是間:

descriptionArea"> 

......還有......

</td> 

朋友建議:

$pattern = '<td="descriptionArea">\s*(.*?)\s*<'; 
$clean = preg_replace("'[\n\r\s\t]'","",$text); // to rid of line breaks 
preg_match($pattern, $clean, $matches); 
print_r($matches); 

,但我得到了以下錯誤:

Warning: preg_match() [function.preg-match]: Unknown modifier 'q' 

我想第二個問題的preg_match是否爲此正確的PHP函數,也。我應該使用ereg嗎?謝謝你的幫助。

回答

4

當使用preg_*功能,第一個字符或圖案被視爲分隔符:

The expression must be enclosed in the delimiters, a forward slash (/), for example. Any character can be used for delimiter as long as it's not alphanumeric or backslash (\). If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Since PHP 4.0.4, you can also use Perl-style () , {} , [] , and <> matching delimiters.
Regular Expressions (Perl-Compatible) – Introduction

所以你不需要逃避或更換&字符別人說。相反,使用適當的分隔符和逃避這些字符的表達式中:

'/&lt;td id=&quot;descriptionArea&quot;&gt;(.*?)&lt;\/td&gt;/' 
+0

還要注意OP的正則表達式不完整:它開始「 2009-02-25 16:39:01

1

我懷疑它正在將&符解釋爲某種控制字符。然而,我找不到支持這一點的參考。

嘗試用[&]替換所有&的實例。

2

你會想逃離「&」,就像wombleton說的那樣,並且還用正斜線包圍你的模式,比如$ pattern =「/ pattern /」;

下面的代碼返回與它的一些醜陋的東西,一個數組,但至少它返回匹配.. :)

$description = " &lt;tr&gt; 
     &lt;td id=&quot;descriptionArea&quot;&gt; 
      Customer request to remove &quot;Intro - 01/13/09&quot; video clip. 
      &lt;br/&gt; 
     &lt;/td&gt; 
    &lt;/tr&gt;"; 

$pattern = "/&lt;td.*[&]quot;descriptionArea[&]quot;[&]gt;\s*(.*?)\s*.*?lt/"; 
$clean = preg_replace("'[\n\r\s\t]'","",$description); // to rid of line breaks 

preg_match($pattern, $clean, $matches); 
var_dump($matches); 

編輯

這裏有一個更好的版本。擺脫所有的HTML編碼的,所以你可以使用標準的HTML的解析正則表達式:

$pattern = '/<.*?id="descriptionArea">(.*?)<\/td>/'; 
$clean = preg_replace("'[\n\r\t]'","",htmlspecialchars_decode($description)); 
preg_match($pattern, $clean, $matches); 
1

如果你想抓住2個常數之間的文本,那豈不是更容易使用好醇」 strpos ?

EDIT

例如

$string = 'text to be >searched< within'; 
$const1 = '>'; 
$const2 = '<'; 
$start = strpos($string, $const1); 
$end = strpos($string, $const2, $start + strlen($const1)); 
$result = substr($string, $start, $end - $start); 

我還沒有運行它,所以它可能是越野車,但你應該明白了。

+0

+1不使用正則表達式! :) – leemes 2011-11-19 15:56:58

0

你對$ pattern使用了什麼?

$pattern = '(?s:descriptionArea&quot;&gt;(.*)&lt;/td&gt;)'; 

我不知道PHP,但RegEx在我測試它時似乎在正則表達式設計器中工作。 (?s :)的選項是'Singleline On'。

馬克

0

你所得到的特定錯誤來自使用該模式的第一個字符作爲分隔符參看preg_ *函數(在這種情況下,「&」),和在第二次出現分隔符後作爲修飾符的所有內容(例如「i」表示不區分大小寫)。

在這種情況下,它認爲您正在尋找lt;td=並且您想要修飾符quot;descriptionArea&quot;&gt;\s*(.*?)\s*&lt;。第一個修飾符「q」沒有意義,它保釋。

相關問題