Reputation: 548
Please help to make preg_replace regex to change html tags to "BB"
<img src="URL" style="max-width: 780px;"/>
<div id="center">TEXT</div>
<a href="http://href.li/?URL" target="blank">$1</a>
<iframe width="780" height="450" src="//www.youtube.com/embed/TEXT" frameborder="0" allowfullscreen></iframe>
<strong>TEXT</strong>
[img]$1[/img]
[center]$1[/center]
[link]$1[/link]
[video]$1[/video]
[strong]$1[/strong]
OK. I did it
%<img src=\"*(.*?)\".*>%
Upvotes: 1
Views: 921
Reputation: 12389
As there is not really a pattern for a simple replace (different attributes from different tags are needed in newly named bb-tags), an indivdual regex for each replacement pair could help:
$rx_map = array(
'~<strong>(.*?)</strong>~is' => '[strong]\1[/strong]',
'~<img\s[^>]*\bsrc="([^"]+)".*?/>~is' => '[img]\1[/img]',
'~<a\s[^>]*\bhref="([^"]+)".*?</a>~is' => '[link]\1[/link]',
'~<iframe\s[^>]*\bsrc="([^"]+)".*?</iframe>~is' => '[video]\1[/video]',
'~<div\s+id="center">(.*?)</div>~is' => '[center]\1[/center]',
);
$str = preg_replace(array_keys($rx_map), array_values($rx_map), $str);
Used modifiers i
for caseless and s
for making the dot also match newlines. This would replace to:
[img]URL[/img]
[center]TEXT[/center]
[link]http://href.li/?URL[/link]
[video]//www.youtube.com/embed/TEXT[/video]
[strong]TEXT[/strong]
test at eval.in; As others mentioned already, regex is generally not recommended for parsing html. Depending on your data, it might not be the best option to use regex here and lead to problems.
Upvotes: 1