Custom BB Codes

enouwee

Non ex transverso sed deorsum
Reaction score
240
If anyone has the patience to explain me, please :). For example, a thing I would like to know would be how to make the url tag. Because, in the url tag you can pass 2 arguments (link and the actual text) and I am confused at it.

Here's the basic matching code, so you can see, what it does:

PHP:
<?php

$string = '[a url="test"]this[B]a test[/a]';

if (preg_match(',\[(a|img)\s+url="([^"]*)"\](.*?)\[/\1\],i', $string, $matches))
{
        print_r($matches);
}

?>

There are tons of ways to proceed from here. I'd add PREG_OFFSET_CAPTURE to the flags passed to preg_match() and replace the BBCode, including URL and body after a thorough validation using substr_replace().
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
You know, you got me even deeper in the fog xD.

No problem, I bet everything will be much clearer, once you see this. It's very easy, didn't even take 30 minutes to write: :D

PHP:
<?php

$string = 'XX[a url="test"]this[B]a test[/a]YY';
$string .= 'ZZ[img url="my_test"]this an image test[/img]TT';

if (preg_match_all(',\[([a-z]+)\s+url="([^"]*)"\](.*?)\[/\1\],i', $string, $matches, PREG_OFFSET_CAPTURE))
{
        for ($i = count($matches[0]) - 1; $i >= 0; $i--)
        {
                $valid = true;

                $len = strlen($matches[0][$i][0]);
                $pos = $matches[0][$i][1];

                $tag = strtolower($matches[1][$i][0]);
                switch ($tag)
                {
                        case 'a':
                        case 'img':
                                // filter your other valid tags here
                                break;
                        default:
                                $valid = false;
                }

                if ($valid == true)
                {
                        // process URL part
                        $url = $matches[2][$i][0];

                        if (empty($url))
                        {
                                $valid = false;
                        }

                        // do other validation here
                }

                if ($valid == true)
                {
                        // process body part
                        $body = $matches[3][$i][0];

                        if (empty($body))
                        {
                                $valid = false;
                        }

                        // do other validation here
                }

                if ($valid)
                {
                        switch ($tag)
                        {
                                case 'img':
                                        $output = '<img src="' . $url . '" alt="' . $body . '" />';
                                        break;
                                case 'a':
                                        $output = '<a href="' . $url . '">' . $body . '</a>';
                                        break;
                        }
                }
                else
                {
                        $output = '';
                }

                $string = substr_replace($string, $output, $pos, $len);

                print "ITERATION USING MATCH $i:\n";
                print "$string\n\n";
        }

        print "FINAL RESULT:\n$string\n";
}


?>
 

monoVertex

I'm back!
Reaction score
460
Meh, I started to understand these functions better. I made myself a piece of code which is supposed to replace the url tags.

PHP:
$text = preg_replace('/(\[url=) (.*?) (\]) (.*?) (\[\/url\])/i','<a href="$2">$4</a>',$text);

I see no syntax problem, and it's supposed to work... However, the url tags are still displayed as literal on the page...
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
PHP:
$text = preg_replace('/(\[url=) (.*?) (\]) (.*?) (\[\/url\])/i','<a href="$2">$4</a>',$text);

I see no syntax problem, and it's supposed to work... However, the url tags are still displayed as literal on the page...

What are you trying to do? I see a lot of useless spaces in that expression.

If you want to replace something like this:
[url.=THIS_IS_MY_URL]THIS IS MY TEXT[/url.] (ignore . due to parsing problem)

better use an expression like:
PHP:
$text = preg_replace(',\[url=\s*(.*?)\s*\]\s*(.*?)\s*\[/url\],i','<a href="$1">$2</a>',$text);

Note that some captures are useless, as you don't use them and \s* matches any number of whitespaces, including 0.
 

monoVertex

I'm back!
Reaction score
460
Thank you! One more question :D. If there are line breaks inside the tags, they are not parsed. How cam I make the function to ignore line breaks?
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
Thank you! One more question :D. If there are line breaks inside the tags, they are not parsed. How cam I make the function to ignore line breaks?

If you want the "." to match newlines, you have to add a "s" modifier, like:
Code:
/line1.*line2/s
Alternatively, the "m" modifier changes the behaviour of "^" to match every "begin of line" and not only the "begin of the string".

The full list of supported modifiers is:
http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
 

monoVertex

I'm back!
Reaction score
460
Hmmm... It's not supposed to match new lines, I can have something like this:

Code:
[font.=verdana]test


test
test
test

test
[/verdana]

This is not parsed and the first "test" is not on a new line.

EDIT: Nvm, studied that list and understood, it's all working now, thanks a lot!
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
EDIT: Nvm, studied that list and understood, it's all working now, thanks a lot!

This works like a charm:

PHP:
<?php

$string ='[font=verdana]test


test
test
test

test
[/font]';

print_r(preg_replace('!\[font=(.*?)\](.*?)\[/font\]!is', '<font face="$1">$2</font>', $string));

?>
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
Yeah, I saw that :D. Gotta spread first :(. You are credited on the page, anyway :D.

If you want to implement your BBCode like that, please don't put my name next to it. phyrex1an already said it the previous posts, I'm going to repeat it:
Don't blindly use that preg_replace() thing without any additional validation steps, as your code will be vulnerable to XSS (cross-site scripting) attacks.

You have to filter both inputs, either by limiting the choices or filtering out malicious content. Rather than saying "(.*?)", you'd use "(arial|times|courier)" to set the font family from a given subset. preg_replace_callback() allows you to do post-processing on the matches: a callback function generates the replacement string.

I put a much larger piece of code in #23, which takes the whole input apart and later replaces it (without preg_replace_callback(), but essentially, both do the same). You can transform and validate the fields as you like before they're inserted back into the text.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • Varine Varine:
    I ordered like five blocks for 15 dollars. They're just little aluminum blocks with holes drilled into them
  • Varine Varine:
    They are pretty much disposable. I have shitty nozzles though, and I don't think these were designed for how hot I've run them
  • Varine Varine:
    I tried to extract it but the thing is pretty stuck. Idk what else I can use this for
  • Varine Varine:
    I'll throw it into my scrap stuff box, I'm sure can be used for something
  • Varine Varine:
    I have spare parts for like, everything BUT that block lol. Oh well, I'll print this shit next week I guess. Hopefully it fits
  • Varine Varine:
    I see that, despite your insistence to the contrary, we are becoming a recipe website
  • Varine Varine:
    Which is unique I guess.
  • The Helper The Helper:
    Actually I was just playing with having some kind of mention of the food forum and recipes on the main page to test and see if it would engage some of those people to post something. It is just weird to get so much traffic and no engagement
  • The Helper The Helper:
    So what it really is me trying to implement some kind of better site navigation not change the whole theme of the site
  • Varine Varine:
    How can you tell the difference between real traffic and indexing or AI generation bots?
  • The Helper The Helper:
    The bots will show up as users online in the forum software but they do not show up in my stats tracking. I am sure there are bots in the stats but the way alot of the bots treat the site do not show up on the stats
  • Varine Varine:
    I want to build a filtration system for my 3d printer, and that shit is so much more complicated than I thought it would be
  • Varine Varine:
    Apparently ABS emits styrene particulates which can be like .2 micrometers, which idk if the VOC detectors I have can even catch that
  • Varine Varine:
    Anyway I need to get some of those sensors and two air pressure sensors installed before an after the filters, which I need to figure out how to calculate the necessary pressure for and I have yet to find anything that tells me how to actually do that, just the cfm ratings
  • Varine Varine:
    And then I have to set up an arduino board to read those sensors, which I also don't know very much about but I have a whole bunch of crash course things for that
  • Varine Varine:
    These sensors are also a lot more than I thought they would be. Like 5 to 10 each, idk why but I assumed they would be like 2 dollars
  • Varine Varine:
    Another issue I'm learning is that a lot of the air quality sensors don't work at very high ambient temperatures. I'm planning on heating this enclosure to like 60C or so, and that's the upper limit of their functionality
  • Varine Varine:
    Although I don't know if I need to actually actively heat it or just let the plate and hotend bring the ambient temp to whatever it will, but even then I need to figure out an exfiltration for hot air. I think I kind of know what to do but it's still fucking confusing
  • The Helper The Helper:
    Maybe you could find some of that information from AC tech - like how they detect freon and such
  • Varine Varine:
    That's mostly what I've been looking at
  • Varine Varine:
    I don't think I'm dealing with quite the same pressures though, at the very least its a significantly smaller system. For the time being I'm just going to put together a quick scrubby box though and hope it works good enough to not make my house toxic
  • Varine Varine:
    I mean I don't use this enough to pose any significant danger I don't think, but I would still rather not be throwing styrene all over the air

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top