M
M
m0dE2014-01-15 09:53:10
PHP
m0dE, 2014-01-15 09:53:10

Replacing BBCode URL with Regular Expression

Good afternoon! There is such a regular expression:
/\[url=(.*)\](.*)\[\/url\]/Usi
And a replacement for it:
<a href="$1" target="_blank">$2</a>
The text of the form
[url=http://google.ru]Сайт гугл[/url]
will be processed normally, but how to make it so that if suddenly there is an empty value in $2, then substitute $1 It
[url=http://google.ru][/url]
will be displayed as:

<a href="http://google.ru" target="_blank">http://google.ru</a>

Is it possible to do this using preg_replace , otherwise I did it through preg_replace_callback for a while:
$text = preg_replace_callback('/\[url=(.*)\](.*)\[\/url\]/Usi', function($match) {
                return '<a href="'.$match[1].'" target="_blank">'.(empty($match[2]) ? $match[1] : $match[2]).'</a>';
            }, $text);

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2014-01-15
@Rsa97

Something like
Make the regular expression non-greedy, otherwise what happens if I insert two links in a row?
And don't forget to check the source data. What happens if you pass a string

[url=http://google.ru]<script src="http://my.xackep.site/zlovred.js"></script>Сайт гугл[/url]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question