1

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=\"*(.*?)\".*>%
2
  • 2
    You can't parse HTML with regex. Commented Aug 31, 2014 at 17:48
  • I get string from mysql like text/plain. preg_replace('/<br\\s*?\/??>/i', '\n', $row['description']); And it works. Maybe I asked the question wrong. Commented Aug 31, 2014 at 18:27

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@user1791020 See updated answer. The opposite thing is possibly a new question :) But sure you'll work that out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.