سؤال

I want to display the most recent posts from my phpbb3 forum on my website, but without the bbcode. so I'm trying to strip the bbcode but without succes one of the posts for example could be:

[quote="SimonLeBon":3pwalcod]bladie bla bla[/quote:3pwalcod]bla bla bladie bla blaffsd
fsdjhgfd dgfgdffgdfg

to strip bbcodes i use the function i found via google, I've tried several other similiar functions aswell:

 <?php
function stripBBCode($text_to_search) {
     $pattern = '|[[\/\!]*?[^\[\]]*?]|si';
     $replace = '';
     return preg_replace($pattern, $replace, $text_to_search);
}
?>

This however doesn't really have any effect.

هل كانت مفيدة؟

المحلول

Here's the one from phpBB (slightly adjusted to be standalone):

/**
* Strips all bbcode from a text and returns the plain content
*/
function strip_bbcode(&$text, $uid = '')
{
    if (!$uid)
    {
        $uid = '[0-9a-z]{5,}';
    }

    $text = preg_replace("#\[\/?[a-z0-9\*\+\-]+(?:=(?:&quot;.*&quot;|[^\]]*))?(?::[a-z])?(\:$uid)\]#", ' ', $text);

    $match = return array(
        '#<!\-\- e \-\-><a href="mailto:(.*?)">.*?</a><!\-\- e \-\->#',
        '#<!\-\- l \-\-><a (?:class="[\w-]+" )?href="(.*?)(?:(&amp;|\?)sid=[0-9a-f]{32})?">.*?</a><!\-\- l \-\->#',
        '#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)">.*?</a><!\-\- \1 \-\->#',
        '#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#',
        '#<!\-\- .*? \-\->#s',
        '#<.*?>#s',
    );
    $replace = array('\1', '\1', '\2', '\1', '', '');

    $text = preg_replace($match, $replace, $text);
}

نصائح أخرى

This will strip bbcode, that is valid (i.e. opening tags matching closing tags).

$str = preg_replace('/\[(\w+)=.*?:(.*?)\](.*?)\[\/\1:\2\]/', '$3', $str);

CodePad.

Reusable Function

function stripBBCode($str) {
   return preg_replace('/\[(\w+)=.*?:(.*?)\](.*?)\[\/\1:\2\]/', '$3', $str);
}

Explanation

  1. \[ match literal [.
  2. (\w+) Match 1 or more word characters and save in capturing group 1.
  3. = Match literal =.
  4. .*? Match ungreedily every character except \n between = and :.
  5. : Match literal :.
  6. (.*?) Match ungreedily every character except \n between : and ] and save in capturing group 2.
  7. \] Match literal ].
  8. (.*?) Match ungreedily every character except \n between : and ] and save in capturing group 3.
  9. \[ Match literal [.
  10. /\1\2 Match previous capturing groups again.
  11. \] Match literal ].

Why don't you use the BBCode parsing facilities that are built in to PHP?

http://php.net/manual/en/book.bbcode.php

Nowadays, use phpbb's own function https://wiki.phpbb.com/Strip_bbcode

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top