What regex can I add to my script that would allow users to have optional parameters in their bb codes?

StackOverflow https://stackoverflow.com/questions/22212975

  •  10-06-2023
  •  | 
  •  

I am writing a custom bb code script in PHP. I would like to be able to give users the option to add different parameters such as width, height, and align to img tags. The script I have works fine if you don't want to alter those attributes... Once I have the regex in place, how would I access those parameters since they would not always correspond to the same numbers ($2) since they are optional?

"'\[img\](.*?)\[\/img\]'is"

A bbcode such as this would look something like this:

[img width=100 height=100 align=right]thelinktotheimage[/img]

Update: I tried to write my own regex for this... basically is supposed to only allow width, height, or align as attributes, the = symbol, and then numeric characters or the string patterns left, right, middle, top, or bottom as their values. For some reason, the regex doesn't match my test string. I have a feeling that I am very close... I hope. Any ideas?

^\[img(((width|height|align)=(([0-9]+)|(left|right|middle|top|bottom)) )+)\](.*?)\[\/img\]$
有帮助吗?

解决方案

It would be difficult to parse a completely arbitrary number of attributes with just regex, but if you only have a maximum of 3 (or some other reasonably small number), you could use something like this:

\[img (?:([a-zA-Z]+)="([a-zA-Z\d]+)")? ?(?:([a-zA-Z]+)="([a-zA-Z\d]+)")? ?(?:([a-zA-Z]+)="([a-zA-Z\d]+)")? ?].+\[\/img]

Here's a link that shows the matches you'll get. As you can see, odd numbered captures are the attribute names while evens are the values. Just delete the double quotes if you're not using them. http://regex101.com/r/bN1jT3

其他提示

So, you could get few preg_match_all() functions but it would get worse with more parameters. What you can do is e.g. use something like this:

<?php
    $bb = "[img width=100 height=100 align=right]thelinktotheimage[/img]<br />[img width=100 height=100 align=right]thelinktotheimage[/img]";
    preg_match_all("'\[img(.{0,40})\](.*?)\[\/img\]'is", $bb, $matches);
    print_r($matches);
?>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top