Answer the question
In order to leave comments, you need to log in
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>
$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);
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question