I
I
Ivan2015-04-29 10:27:41
PHP
Ivan, 2015-04-29 10:27:41

How to write a regular expression for a complex bb-code?

The following bb tag is generated on my site
[br][img src="images/20150429064557608.jpg" width="1500" class="Class name" alt="Image title"][br]
All parameters including width and class name may change, but that's not the point.
Some parameters may not exist at all, for example, there may be no alt
[br][img src="images/20150429064557608.jpg" width="1500" class="Class name"][br]
We need to translate this complex bb code using a regular expression into html tag, correctly, and so as to exclude hacking through it.
This time I ask you to help me write this regex (a ready-made recipe), and then give me some literature on the topic of regexes for dummies (Google rules), otherwise I’m already ashamed to ask people to help compose regexes. I promise that I will deal with them myself ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Dugin, 2015-04-29
@iwqn

1) Obvious solution: replace [] with <> and discard [br]
2) What does it mean to "exclude hacking through it"? Set the task more specifically.
Python regex example:

>>> import re
>>> text = '[br][img src="images/20150429064557608.jpg" width="1500" class="class_name" alt="pic_title"][br]'
>>> items = re.findall(r'(?:\b(src|width|class|alt)="([^"]*)")+', text)
>>> items
[('src', 'images/20150429064557608.jpg'), ('width', '1500'), ('class', 'class_name'), ('alt', 'pic_title')]
>>> line = '<img %s>' % ' '.join('%s="%s"' % (param, value) for param, value in items)
>>> line
'<img src="images/20150429064557608.jpg" width="1500" class="class_name" alt="pic_title">'

L
Leonid Sysoletin, 2015-04-29
@sysoletin

First three Google results for "php bbcode parse"
with explanation
without explanation
for bundle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question