2012-03-13 5 views
1

私は<pre>タグ内の属性をオプションのクラスタグと共に取得しようとしています。私はすべての属性をキャプチャするのではなく、可能であればクラス属性値を見つけるよりも、ある正規表現でクラスタグの内容をキャプチャしたいと思います。クラスタグはオプションなので、私は?を追加しようとしましたが、次の正規表現が最後のキャプチャグループを使用してしかキャプチャしません。クラスはキャプチャされず、その前の属性もキャプチャされません。Regexオプションのクラスタグ

// Works, but class isn't optional 
'(?<!\$)<pre([^\>]*?)(\bclass\s*=\s*(["\'])(.*?)\3)([^\>]*)>' 

// Fails to match class, the whole set of attributes are matched by last group 
'(?<!\$)<pre([^\>]*?)(\bclass\s*=\s*(["\'])?(.*?)\3)([^\>]*)>' 

e.g. <pre style="..." class="some-class" title="stuff"> 

EDIT:

私はこれを使用して終了:

$wp_content = preg_replace_callback('#(?<!\$)<\s*pre(?=(?:([^>]*)\bclass\s*=\s*(["\'])(.*?)\2([^>]*))?)([^>]*)>(.*?)<\s*/\s*pre\s*>#msi', 'CrayonWP::pre_tag', $wp_content); 

これは、タグ内の空白を可能にしても、クラス属性の前と後のものを隔てるだけでなく、すべてのキャプチャ属性。

その後、コールバックは場所で物事を置く:

public static function pre_tag($matches) { 
    $pre_class = $matches[1]; 
    $quotes = $matches[2]; 
    $class = $matches[3]; 
    $post_class = $matches[4]; 
    $atts = $matches[5]; 
    $content = $matches[6]; 
    if (!empty($class)) { 
     // Allow hyphenated "setting-value" style settings in the class attribute 
     $class = preg_replace('#\b([A-Za-z-]+)-(\S+)#msi', '$1='.$quotes.'$2'.$quotes, $class); 
     return "[crayon $pre_class $class $post_class] $content [/crayon]"; 
    } else { 
     return "[crayon $atts] $content [/crayon]"; 
    } 
} 

答えて

4

あなたは先読みアサーションにclass属性のキャプチャグループを入れて、それをオプションにできます。今すぐ

'(?<!\$)<pre(?=(?:[^>]*\bclass\s*=\s*(["\'])(.*?)\1)?)([^>]*)>' 

$2が含まれていますclass属性の値が存在する場合はその値を返します。

(?<!\$)    # Assert no preceding $ (why?) 
<pre     # Match <pre 
(?=     # Assert that the following can be matched: 
(?:     # Try to match this: 
    [^>]*    # any text except > 
    \bclass\s*=\s*  # class = 
    (["\'])   # opening quote 
    (.*?)    # any text, lazy --> capture this in group no. 2 
    \1     # corresponding closing quote 
)?     # but make the whole thing optional. 
)      # End of lookahead 
([^\>]*)>    # Match the entire contents of the tag and the closing > 
+0

壮大な、ありがとう! –

関連する問題