2012-04-23 32 views
1
function bb_parse($string, $tags = 'b|i|u|quote|url|img|youtube|user') { 
    $replacement = 0; 
    while (preg_match_all('`\[('.$tags.')=?(.*?)\](.+?)\[/\1\]`', $string, $matches)) foreach ($matches[0] as $key => $match) { 
     list($tag, $param, $innertext) = array($matches[1][$key], $matches[2][$key], $matches[3][$key]); 
     switch ($tag) { 
      case 'b': $replacement = '<strong>'.$innertext.'</strong>'; break; 
      case 'i': $replacement = '<em>'.$innertext.'</em>'; break; 
      case 'u': $replacement = '<span style="text-decoration: underline;">'.$innertext.'</span>'; break; 
      case 'quote': $replacement = '<div class="quote"><div class="quote-author">'.($param ? 'Quote by: '.$param : 'Quote').'</div>'.$innertext.'</div>'; break; 
      case 'url': $replacement = '<a href="'.($param ? $param : $innertext).'">'.$innertext.'</a>'; break; 
      case 'user': $replacement = '<a href="'.url('user/'.($param ? $param : $innertext)).'">'.$innertext.'</a>'; break; 
      case 'img': $replacement = '<img src="'.$innertext.'" style="max-width: 640px;"/>'; break; 
      case 'youtube': 
      $videourl = parse_url($innertext); 
      parse_str($videourl['query'], $videoquery); 
      if (strpos($videourl['host'], 'youtube.com') !== FALSE) $replacement = '<div><iframe width="755" height="425" src="http://www.youtube.com/embed/'.$videoquery['v'].'" frameborder="0" allowfullscreen></iframe></div>'; 
      break; 
     } 
     $string = str_replace($match, $replacement, $string); 
    } 
    return $string; 
} 

如果我使用了[quote]用换行符例如,它会输出这样的:bbcode_parser不会允许换行符

[quote]This is {LINEBREAK} 
a test[/quote] 

而不是以此为应该

<div class="quote"><div class="quote-author">Quote</div>This is {LINEBREAK} 
a test</div> 

任何人都有一个想法?

+0

尝试添加's'修改到您正则表达式(['PCRE_DOTALL'(http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php))。 – DaveRandom 2012-04-23 18:25:58

+0

你是什么意思?或者在哪里? – Qzen 2012-04-23 18:26:47

+0

将表达式字符串改为''#\ [('。$ tags。')=?(。*?)\](。+?)\ [/ \ 1 \]#s'' - 注意's''在最后 – DaveRandom 2012-04-23 18:27:57

回答

0

您可以在RegEx上使用s修饰符来表示'单线模式'。点(.)默认情况下不匹配换行符。使用s修饰符,它可以。

preg_match_all('`\[('.$tags.')=?(.*?)\](.+?)\[/\1\]`s', $string, $matches)