I'm using preg_replace to convert all BBCode to HTML but can't get img tags to work. Here is my code:
$search = array (
'/(\[b\])(.*?)(\[\/b\])/m',
'/(\[i\])(.*?)(\[\/i\])/m',
'/(\[u\])(.*?)(\[\/u\])/m',
'/(\[ul\])(.*?)(\[\/ul\])/m',
'/(\[li\])(.*?)(\[\/li\])/m',
'/(\[user=)(.*?)(\])(.*?)(\[\/user\])/m',
'/(\[url=)(.*?)(\])(.*?)(\[\/url\])/m',
'/(\[url\])(.*?)(\[\/url\])/m',
'/(\[img=)(.*?)(\])(.*?)(\[\/img\])/m',
'/(\[quote\])(.*?)(\[\/quote\])/m',
'/(\[code\])(.*?)(\[\/code\])/m',
);
$replace = array (
'<strong>$2</strong>',
'<em>$2</em>',
'<u>$2</u>',
'<ul>$2</ul>',
'<li>$2</li>',
'<a href="../login/profile?u=$2" target="_blank">$2</a>',
'<a href="$2" target="_blank">$4</a>',
'<a href="$2" target="_blank">$2</a>',
'<img src="$4"></img>',
'<quote>$2</quote>',
'<code>$2</code>'
);
$string = preg_replace($search, $replace, $string);
Right now it creates an image tag with the link in but adds ]
to the start and end of the link so it doesn't display the image correctly.
EDIT:
This is cause by me converting links to anchor tags and it's conflicting within the [img] BBCode.
$url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/';
$string = preg_replace($url, '[url=$0]$0[/url]', $string);
Several points to make:
/
to~
so that you don't have to escape the/
characters that exist inside your pattern.]
to be the end of a character class if a character class is opened. For this reason, I am not escaping any]
characters.^
or$
), them
pattern modifier is needless.i
pattern flag/modifier.$1
in the replacement string.(*SKIP)(*FAIL)
"disqualifies" these unwanted substrings.Code: (Demo)
Output: