1

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?

2 Answers 2

1

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.

0
0

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?

2
  • @user3904923 did this help any or do you want more help? Sep 15, 2014 at 18:15
  • Actually it does. Thanks for your help. I didnt say it was wrong, it just didnt managed it like it should. But The other regex seems to work. :)
    – w a v e z
    Sep 15, 2014 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.