phpplaceholdertext-parsingbbcode

Parse BBCode-style tags to access tag name and contained text


I'm trying to parse some text for example:

$text = "Blah blah [a]findme[/a] and [b]findmetoo[b], maybe also [z]me[/z].";

What I have now is:

preg_match_all("/[*?](.*?)[\/*?]/", $text, $matches);

Which doesn't work unfortunately.

Any ideas how to parse, return the node key and the corresponding node value?


Solution

  • Well firstly by you not putting () around your *? your not matching the tag name, and secondly, using [*?] will match multiple [ until the ] where you want to match inside, so you should be doing [(.*?)] and [\/(.*?)]

    You would have to try something along the lines of:

    /\[(.*?)\](.*?)\[\/(.*?)\]/is
    

    this is not guaranteed to work but will get you closer.

    you could also do:

    /\[(.*?)\](.*?)\[\/\1\]/is
    

    and then foreach result loop recursively until preg_match_all returns false, that's a possible way how to do nesting.