2012-10-04 78 views
1

我有類似以下一段HTML代碼:正則表達式PCRE表達

<td width="24%"><b>Something</b></td> 
      <td width="1%"></td> 
      <td width="46%" align="center"> 
      <p><b> 
    needed 
    value</b></p> 
      </td> 
      <td width="28%" align="center"> 
      &nbsp;</td> 
     </tr> 

什麼是一個很好的正則表達式字Something我以後提取第一文本節點(不是標籤,但裏面的文字)意思是我想提取

 needed 
    value 

沒有什麼更多。

我不能找出一個工作正則表達式模式在PHP中。

編輯: 我不解析整個HTML文檔,但它的幾行所以我要的是它使用正則表達式並沒有HTML解析器做。

+1

在PHP或Perl? –

+0

「php中的模式」...謝謝:) –

+3

不要使用正則表達式解析HTML。 [見這篇文章](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)爲什麼。 –

回答

4

忽略用正則表達式解析HTML潛在的問題,下面的模式應該與你的示例代碼:

Something(?:(?:<[^>]+>)|\s)*([\w\s*]+) 

這將匹配Something,其次是HTML標籤(或空格)的任何名單,並在第二天塊匹配文本,\w(包括空格)。

您可以像這樣在PHP的preg_match()方法使用:

if (preg_match('/Something(?:(?:<[^>]+>)|\s)*([\w\s*]+)/', $inputString, $match)) { 
    $matchedValue = $match[1]; 
    // do whatever you need 
} 

正則表達式解釋:

Something   # has to start with 'Something' 
(?:    # non-matching group 
    (?:   # non-matching group 
     <[^>]+> # any HTML tags, <...> 
    ) 
    | \s   # OR whitespace 
)*    # this group can match 0+ times 
(
    [\w\s*]+  # any non-HTML words (with/without whitespace) 
) 
+2

謝謝!這就是我所需要的。我覺得這個解釋也很有用。 –