dqwh1202 2011-03-08 22:36
浏览 60

RegEx从img标签获取src,width和height属性(在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" />

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]
  • 写回答

2条回答 默认 最新

  • duanpo1821 2011-03-08 22:53
    关注

    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)

    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路