2012-10-07 2 views
1

가능한 중복 : 나는 정규식에 문제가
php regex [b] to <b>정규식 중첩 포럼 따옴표 (BBCode는)

, 나는 절대 정규식 멍청한 놈입니다. HTML을 'BBCode'로 다시 변환하려고 할 때 잘못된 점이 있는지 알 수 없습니다.

누군가 'unquote'함수를 살펴보고 내가 작성한 명백한 실수를 말할 수 있습니까? (나는 명백하지 않은 오류를 항상 발견하기 때문에 분명하다.)

참고 : Regex를 재귀 적으로 사용하지는 않는다. 내 머리를 감당할 수 없어 이미 인용문을 정렬하는 방식으로 시작했다. 그들은 중첩되어 있습니다. 샘, 사전에

<html> 
<head> 
    <style> 
    body { 
     font-family: sans-serif; 
    } 
    .quote { 
     background: rgba(51,153,204,0.4) url(../img/diag_1px.png); 
     border: 1px solid rgba(116,116,116,0.36); 
     padding: 5px; 
    } 

    .quote-title, .quote_title { 
     font-size: 18px; 
     margin: 5px; 
    } 

    .quote-inner { 
     margin: 10px; 
    } 
    </style> 
</head> 
<body> 
    <?php 
    $quote_text = '[quote=VCMG][quote=2xAA]DO RECURSIVE QUOTES WORK?[/quote]I have no idea.[/quote]'; 
    $quoted = quote($quote_text); 
    echo $quoted.'<br><br>'.unquote($quoted); ?> 
</body> 

감사 :

<?php 
function quote($str){ 
    $str = preg_replace('@\[(?i)quote=(.*?)\](.*?)@si', '<div class="quote"><div class="quote-title">\\1 wrote:</div><div class="quote-inner">\\2', $str); 
    $str = preg_replace('@\[/(?i)quote\]@si', '</div></div>', $str); 
    return $str; 
} 

function unquote($str){ 
    $str = preg_replace('@\<(?i)div class="quote"\>\<(?i)div class="quote_title"\>(.*?)wrote:\</(?i)div\><(?i)div class="quote-inner"\>(.*?)@si', '[quote=\\1]\\2', $str); 
    $str = preg_replace('@\</(?i)div\></(?i)div\>@si', '[/quote]', $str); 
} 
?> 

이 그것을 테스트하는 데 도움 그냥 코드입니다.

답변

3

글쎄, 당신은 quote-title 또는 quote_title PHP 클래스를 설정하여 시작할 수 있지만 일관성을 유지.

그런 다음 return $str;을 두 번째 함수에 추가하면 거의 다 왔을 것입니다.

그리고 당신은 당신의 정규식을 단순화 할 수는 조금의 :

function quote($str){ 
    $str = preg_replace('@\[quote=(.*)\]@siU', '<div class="quote"><div class="quote-title">\\1 wrote:</div><div class="quote-inner">', $str); 
    $str = preg_replace('@\[/quote\]@si', '</div></div>', $str); 
    return $str; 
} 

function unquote($str){ 
    $str = preg_replace('@<div class="quote"><div class="quote-title">(.*) wrote:</div><div class="quote-inner">@siU', '[quote=\\1]', $str); 
    $str = preg_replace('@</div></div>@si', '[/quote]', $str); 
    return $str; 
} 

그러나 다른 통화를 시작하고 따옴표의 끝 태그로 대체 조심. 나는 너비가 </div></div> 인 다른 bbcode가 생기면 unquote가 이상한 행동을 일으킬 수 있다고 생각한다. 하나로, 또한

do { 
    $str = preg_replace(REGEX , REPLACE , $str , -1 , $c); 
} while($c > 0); 

수행 더 이상 경기가 없을 때까지

<div class="quote">Blah <div class="quote">INCEPTION!</div> More blah</div> 

가 반복해서 정규식을 실행

+0

> 그 빌어 먹을 반환 ... 나는 그것이 명백한 무엇인가 알았다. 단순화에 감사드립니다. 훨씬 더 좋습니다! – 2xAA

0

개인적으로, 나는 결과 HTML은 기본적으로 사실을 활용 이 쉽게하기 위해 정규식 :

'(\[quote=(.*?)\](.*?)\[/quote\])is' 
'<div class="quote"><div class="quote-title">$1 wrote:</div><div class="quote-inner">$1</div></div>' 
+0

나는 물음표를 사용하여 한정어의 "욕심을 거꾸로하는"어딘가를 읽었을 때 단순히 게으르게 만들지 않는다고 생각합니다. 따라서 U 옵션을 사용했기 때문에 한정 기호가 게으르다면, 당신은 원하지 않는'. *? '를 사용하여 다시 욕심을 갖게됩니다. – Cimbali

+0

아, 그래. 저는 U가 "유니 코드"라고 생각했지만 소문자 인 "u"입니다. 좋아, 편집 할거야. –