2012-04-19 61 views
4

我有一個PHP preg_match_all和REGEX問題。使用REGEX引號內的轉義引號

我有以下代碼:

<?php 

$string= 'attribute1="some_value" attribute2="<h1 class=\"title\">Blahhhh</h1>"'; 

preg_match_all('/(.*?)\s*=\s*(\'|"|&#?\w+;)(.*?)\2/s', trim($string), $matches); 

print_r($matches); 

?> 

似乎不是皮卡逃過實例的報價,我想在HTML通過與報價。我已經嘗試了很多解決方案,用引號REGEX修補程序中的基本引號,但似乎沒有任何解決方案適用於我。我似乎無法將它們正確放置在這個預先存在的REGEX中。

我不是REGEX高手,有人能指點我嗎?

我想達到的效果是這樣的:

Array 
(
    [0] => Array 
     (
      [0] => attribute1="some_value" 
      [1] => attribute2="<h1 class=\"title\">Blahhhh</h1>" 
     ) 

    [1] => Array 
     (
      [0] => attribute1 
      [1] => attribute2 
     ) 

    [2] => Array 
     (
      [0] => " 
      [1] => " 
     ) 

    [3] => Array 
     (
      [0] => some_value 
      [1] => <h1 class=\"title\">Blahhhh</h1> 
     ) 
) 

感謝。

+1

我們可以知道你在這段代碼中究竟做了什麼? – anubhava 2012-04-19 19:28:10

+0

你想要得到什麼? – 2012-04-19 19:28:59

回答

1

您可以用negative lookbehind assertion解決這個問題:

'/(.*?)\s*=\s*(\'|"|&#?\w+;)(.*?)(?<!\\\\)\2~/' 
           ^^^^^^^^^ 

收盤報價不應由\預先考慮。給我:

Array 
(
    [0] => Array 
     (
      [0] => attribute1="some_value" 
      [1] => attribute2="<h1 class=\"title\">Blahhhh</h1>" 
     ) 

    [1] => Array 
     (
      [0] => attribute1 
      [1] => attribute2 
     ) 

    [2] => Array 
     (
      [0] => " 
      [1] => " 
     ) 

    [3] => Array 
     (
      [0] => some_value 
      [1] => <h1 class=\"title\">Blahhhh</h1> 
     ) 
) 

這正則表達式是不完美的,因爲實體您的,但在那裏作爲分隔符,如引號,可以用\轉義爲好。不知道這是否真的有意。

另請參閱這個偉大的問題/答案:Split string by delimiter, but not if it is escaped

+0

這個效果很好,甚至包含\ n字符。感謝偉大的答案Hakre! – cmfolio 2012-04-19 20:50:06