开发者

RegExp to get src, width and height attributes from img tags (in PHP)

I have a random, long string of html code (user-entered) - I need to check it for img tags and the respective widths/heights and replace every image instance with a string of proprietary code, so for example

Hello world <img src="http://example.com/image.jpg" width="320" height="240" /> this is some random text <img src="http://example.com/cutepuppy.jpg" width="150" height="200" />开发者_Python百科

Needs to be replaced with

Hello world [img:http://example.com/image.jpg w:320 h:240] this is some random text [img:http://example.com/cutepuppy.jpg w:150 h:200]


The regex you'll need will be like :

<img.*src=["'](.*)["'].*width=(\d+).*height=(\d+).*/>

Then I think you can make the replacement with the correct php function (preg_replace I guess?) and use backreferences like \1for the fist matching parenthesis and so on, to retrieve the different values.

But the HTML syntax is too complex to be used with regexp like you will read on every stackoverflow posts on the subject. For example, the example here won't work if you inverse the width and the height.

I think you can find better solutions to your problem just by browsing SO. (Example : SO)


It doesn't answer your question, but wouldn't it be easier to:

list($width, $height, $type, $attr) = getimagesize("http://example.com/image.jpg");

and then you don't need to rely on valid html in the markup.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜