Help needed with stackbased UBB parser

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Reveller
Forum Newbie
Posts: 1
Joined: Tue Dec 02, 2008 11:04 am

Help needed with stackbased UBB parser

Post by Reveller »

I'm trying to build a (non-OO) stackbased UBB parser. I have a sample string:

Code: Select all

This is [b class="red"]a[/b] teststring [i]with[/i] [foo bar="bla" bla="foo"] tags.
I want to filter the three tags (b, i and foo) into an array:

Code: Select all

Array (
  [TAG] => B
  [POS1] => 7
  [POS2] => 22
  [ATTR] => Array (
    [class] => red
  )
)
 
// etc...
I now have the following code, but have a problem with it. After detecting the first tag (b), I have to set a $stackpointer or something, so that it is remembered where I have to start iterating through $text the second time around. The way it is coded now, ubb_parse gets into an infinite loop. Could anybody give me a hint on how to solve this?

Code: Select all

 
function ubb_search_tag($text) {
  $pos1 = -1;
  $tag = "";
     
  while ($tag == "") {
    $pos1 = strpos($text, "[", $pos1 + 1);
    $pos2 = strpos($text, "]", $pos1);
    
    if ($pos1 == 0 && $pos2 > $pos1) {
      $tag = substr($text, 1, $pos2 - 1);
      $tagtext = $tag;
      $space = strpos($tag, " ");
      $equal = strpos($tag, "=");
      if ($space > -1) $tag = substr($tag, 0, $space);
      if ($equal > -1) $tag = substr($tag, 0, $equal);
      return array("TAG" => strtoupper($tag), "POS1" => $pos1, "POS2" => $pos2 + 1, "TAGTEXT" => $tagtext);                 
    }
    else if ($pos1 > -1 && $pos2 > $pos1) {
      if (substr($text, $pos1 - 1, 1) == "\\") {
        $pos1 += 2;
      }
      else {
        $tag = substr($text, $pos1 + 1, $pos2 - $pos1 - 1);
        $tagtext = $tag;
        $space = strpos($tag, " ");
        $equal = strpos($tag, "=");
        if ($space > -1) $tag = substr($tag, 0, $space);
        if ($equal > -1) $tag = substr($tag, 0, $equal);
        return array("TAG" => strtoupper($tag), "POS1" => $pos1, "POS2" => $pos2 + 1, "TAGTEXT" => $tagtext);
      }
    }
    else {
      return array("TAG" => "", "POS1" => -1, "POS2" => -1, "TAGTEXT" => "");
    }
  }
}
 
function ubb_parse($text) {
  $text = str_replace("\r", "", $text);
  $text = trim($text);
  $tag  = ubb_search_tag($text);
  
  print_r($tag);
  
  //while ($tag["TAG"] != "") {
  //  $tag = ubb_search_tag($text);
  //  print_r($tag);
  //}
}
 
$text = 'This is [b class="red"]a[/b] teststring [i]with[/i] [foo bar="bla" bla="foo"] tags.';
ubb_parse($text);
Any help would be greatly appreciated!
Post Reply