PHP BBCode Parser

I have a tiny bbcode parser which works very well, except pre and code tags. I need to make pre and code tags ignored by the whole parser function. How would I achive this ? If any one have an idea please let me know.

What I'm trying to do is when I use <pre> or <code> tags it will ignore the bbcode used inside, but parse it everywhere else on the page. I think it can be achived with regex and preg_match or preg_replace some how.

function parse($text) {

  $search = array(
    '/**(.*?)**/is',  // bold
    '///(.*?)///is',  // italic
    '/__(.*?)__/is',    // underline
  ); #search

  $replace = array(
    '<b>$1</b>',
    '<i>$1</i>',
    '<u>$1</u>',
  ); #replace

  return preg_replace($search, $replace, $text);

} #parse



<pre>

  ** Bold Text **
  // Italic Text //
  __ Uderline Text __

</pre>

<code>

  ** Bold Text **
  // Italic Text //
  __ Uderline Text __

</code>

Any help will be apreceated. Thank you.


First of all, that's not BBCode. BBCode uses [ and ] as delimiters to mimic common HTML markup tags. What you have there, is something similar to Markdown or reStructuredText.

Secondly, you replacement algorithm is extremely simple and likely to give you much trouble in the future. If you are not merely doing this to learn how to code in PHP, I'd suggest you use existing parsers that already do what you want to do, like PHP Markdown, PHP reStrucuredText or PHP BBCode Parser.

Now, as for your actual question: This will not be easy, but you can start with altering your regexes so they only apply if they are not inside <pre> tags like this: (untested)

'/(?<!<pre>).*?**(.*?)**.*?(?!</pre>)/is',  // bold
链接地址: http://www.djcxy.com/p/29872.html

上一篇: PHP正则表达式bbcode返回空白

下一篇: PHP BBCode解析器