Reputation: 17
I really don't get the right solution.
My standard img replace code is:
preg_replace('~\[img](.*?)\[/img\]~s','<img src="$1" />',$text);
Of course it works. But im trying to replace the bbcode if width and height is set. But thats optional, so it should work also if only 1 dimension is set or nothing.
The bbcode looks like: [img=12x12]link of the image[/img]
So the bbcode should look like:
preg_replace('~\[img=(.*?)x(.*?)\](.*?)\[/img\]~s','<img width="$1" height="$2" src="$3" />',$text);
I guess I got it wrong. Anybidy knows how to solve this?
Upvotes: 1
Views: 772
Reputation: 3799
Try this regex:
preg_replace('~\[img=?(\d+)?x?(\d+)?\](.*?)\[/img\]~s','<img width="$1" height="$2" src="$3" />',$text);
The way you coded it, it wouldn't match all 3 cases you wanted: [img]
, [img=NN]
, and [img=NNxNN]
. It would only match in the case both dimensions were provided.
Upvotes: 1
Reputation: 4238
Your regexp should definitely work. I would have used \d+
though which makes sure the value exists and are of numeric type:
~\[img=(\d+)x(\d+)\](.*?)\[/img\]~s
What error are you getting with your code, or rather, what string are you expecting to match but you don't?
Upvotes: 0