<?php
$bbcodes = [
'Look at this:https://www.example.com/example?ohyeah=sure#okay this is a raw link',
'No attibute bbcode url: [url]http://example.com/x1[/url]',
'A url with link and link text: [url=http://example.com/x2]x2[/url]',
'Image with "ignorable" text: [IMG=sumpthing.jpg]sumpthing[/IMG]',
'Image: [img=sumpinelse][/img]'
];
$search = array (
// ...
'~\[url=((?:ht|f)tps?://[a-z\d.-]+\.[a-z]{2,3}/\S*?)](.*?)\[/url]~i',
'~\[url]((?:ht|f)tps?://[a-z\d.-]+\.[a-z]{2,3}/\S*?)\[/url]~i',
// ...
'~\[img=(.*?)].*?\[/img]~i', // if you want the possibility of dot matching newlines, add s pattern modifier
// ...
'~(?:<a.*?</a>|<img.*?</img>)(*SKIP)(*FAIL)|\bhttps?://.+?(?=\s|$)~im' // mop up any remaining links that are not bbtagged
);
$replace = array (
// ...
'<a href="$1" target="_blank">$2</a>',
'<a href="$1" target="_blank">$1</a>',
// ...
'<img src="$1"></img>',
// ...
'<a href="$0" target="_blank">$0</a>',
);
var_export(preg_replace($search, $replace, $bbcodes));
array (
0 => 'Look at this:<a href="https://www.example.com/example?ohyeah=sure#okay" target="_blank">https://www.example.com/example?ohyeah=sure#okay</a> this is a raw link',
1 => 'No attibute bbcode url: <a href="http://example.com/x1" target="_blank">http://example.com/x1</a>',
2 => 'A url with link and link text: <a href="http://example.com/x2" target="_blank">x2</a>',
3 => 'Image with "ignorable" text: <img src="sumpthing.jpg"></img>',
4 => 'Image: <img src="sumpinelse"></img>',
)
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
array (
0 => 'Look at this:<a href="https://www.example.com/example?ohyeah=sure#okay" target="_blank">https://www.example.com/example?ohyeah=sure#okay</a> this is a raw link',
1 => 'No attibute bbcode url: <a href="http://example.com/x1" target="_blank">http://example.com/x1</a>',
2 => 'A url with link and link text: <a href="http://example.com/x2" target="_blank">x2</a>',
3 => 'Image with "ignorable" text: <img src="sumpthing.jpg"></img>',
4 => 'Image: <img src="sumpinelse"></img>',
)