2012-03-13 10 views
1

<pre> 태그의 속성을 선택적 클래스 태그와 함께 캡처하려고합니다. 가능하면 모든 속성을 포착하고 클래스 속성 값을 찾지 않고 하나의 정규식에서 클래스 태그의 내용을 캡처하고 싶습니다. 클래스 태그는 선택적이므로 ?을 추가하려고 시도했지만 다음 정규식이 마지막 캡처 그룹을 사용하여 캡처하게됩니다. 클래스는 캡처되지 않으며 그 전에는 속성이 없습니다.정규식 선택적 클래스 태그

// 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"> 

편집 : 나는이를 사용하여 종료

:

$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

장엄한 감사합니다! –