ShoeLace1291 Posted March 6, 2014 Share Posted March 6, 2014 (edited) I am trying to write my custom bb code parser in PHP. In my img tags, I want to be able to allow users to add optional parameters(width, height, and align). The combinations of attributes may be different between tags... for instance, some tags may only have the align attribute, others may have only width and height, others may have all three, or none of them. So basically my regex should match img tags with either width, height, or align as attributes... either numerical characters or the strings left, right, middle, top or bottom as the values, equal(=) symbol in between the attribute and the value, and spaces. This is the regex: ^\[img(((width|height|align)=(([0-9]+)|(left|right|middle|top|bottom)) )+)\](.*?)\[\/img\]$This is the test string: [img width=100 height=100 align=right]thelinktotheimage[/img] http://regex101.com/r/uT1lU2 Thanks in advance. Edited March 6, 2014 by ShoeLace1291 Quote Link to comment https://forums.phpfreaks.com/topic/286750-allowing-optional-parameters-in-custom-bbcode-parser/ Share on other sites More sharing options...
.josh Posted March 6, 2014 Share Posted March 6, 2014 There are a number of issues wrong with your regex. Some things are just wrong for what you are individually trying to match (e.g. spacing, allowing for bad matches like align=100), and some things are wrong because what you are trying to match for in regex101 more than likely doesn't really match your real-world context (e.g. I somehow doubt you're really parsing a list of bbcodes. More likely is you are ultimately trying to find them within a bunch of arbitrary text like a forum post and replace them with html markup). So, here is an example of how to find and replace them: $content = preg_replace_callback( '~\[img((?:\s+(??:width|height)=\d+|align=(?:left|right|middle|top|bottom)))+)\s*\](.*?)\[\/img\]~i', function ($m) { $m[1] = array_filter(preg_split('~\s+~',$m[1])); array_walk( $m[1], function (&$a) { $a = explode('=',$a); // this is where you would do something with attribute. // $a[0] is name and $a[1] is value. The code below just // translates it to e.g. height='100' but you may want to do // something else. For example, align isn't supported by html5 // so in reality you'll prolly want to instead check if $a[0]=='align' // and then build a style='..' attrib instead $a = "{$a[0]}='{$a[1]}'"; } ); return "<img src='{$m[2]}' ".implode(' ',$m[1])."/>"; }, $content ); Quote Link to comment https://forums.phpfreaks.com/topic/286750-allowing-optional-parameters-in-custom-bbcode-parser/#findComment-1471651 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.