PHP preg 匹配/替换?
我需要读取字符串 $mysting 并将所有 ex 事件替换
<img src="dummypic.jpg alt="dummy pic">
为,
<img src="dummypic.jpg alt="dummy pic" title="dummy pic">
换句话说,在缺少的标题处添加标题,并使标题标签具有与 alt 标签相同的值。
有些事件我有额外的参数,如边框、宽度、高度 - 这些应该保持不变......
I need to read the string $mysting and replace all incident of e.x.
<img src="dummypic.jpg alt="dummy pic">
with
<img src="dummypic.jpg alt="dummy pic" title="dummy pic">
in other words add the title where it is missing, and make the title tag have the same value as the alt tag.
some incident my have additional parameters like border, with, height - and these should be left untouched ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不是使用正则表达式,而是查看 PHP DOMDocument 来修改属性,特别是如果会有任何复杂性。
Rather than a regex, have a look into PHP DOMDocument to modify attributes, especially if there will be any complexity.
您可以使用 phpQuery 或 QueryPath 来执行此操作:
尽管在这个简单的情况下诉诸正则表达式可能是可行的
:(使用 preg_replace_callback 来确保不存在 title= 属性会更有意义。)
You could use phpQuery or QueryPath to do that:
Though it might be feasible in this simple case to resort to an regex:
(It would make more sense to use preg_replace_callback to ensure no title= attribute is present yet.)
您确实想使用 html 解析器而不是正则表达式来执行此操作。正则表达式不适合 html 处理。
You really want to do this using an html parser instead of regexes. Regexes are not suited for html processing.
我的答案是一个众所周知的答案的链接!
RegEx 匹配开放标记(XHTML 自包含标记除外)
My answer is a link to a well known answer!
RegEx match open tags except XHTML self-contained tags
我通常在这些类型的情况下编写快速的脏黑客(通常使用结构化数据,可能存在不一致,例如模板引擎标签、条件等)。在我看来,这是一个糟糕的解决方案,但我可以超快地敲出这些脚本。
例如。
I usually write quick dirty hacks in these types of situations (usually working with structured data, that might have inconsistencies such as templating engine tags, conditionals, etc.). IMO its a terrible solution, but I can bang out these scripts super fast.
Eg.