PHP preg_replace 替换 img 标签并将其移动到 html 文本中
我正在开发一个移动网络,其内容来自外部 XML,并且我在标签方面遇到了问题。它们带有样式属性,我认为在显示内容之前使用 php 中的 preg_replace 可以很容易地删除这些属性。当在文本中找到 img 标签时就会出现问题...类似于:“Hello 我的名字是 Alfred
。如果我只是删除样式属性(通常带有 display:float),图像就会破坏文本,使其难以阅读。
”
我的解决方案是:使用 preg_replace,我“清理”所有图像标签,但是然后我需要获取这些标签并将它们放置在下一个
之后, 等(每个段落标记的结尾)。我认为它至少会让页面更具可读性和组织性。
问题:不知道如何获取每个img标签的索引,就在我清理它之后,然后找到下一个段落末尾将其放置在那里。
示例-->
之前:
Hell<img .../>o my name is Alfred.<br/>
<p>I come <img .../>from England</p>
之后:
Hello my name is Alfred<br/>
<img .../>
<p>I come from England</p>
<img .../>
提前致谢。
编辑 ---
我的疑问是:如果我在文本中找到了 img 标签()(可能使用 preg_replace,因为我首先需要找到一个img 标签,验证其属性并在必要时更改它们),如何获取整个字符串内的索引(整个字符串是指整个 html 文档作为字符串读取),以便我可以获取整个标签并将其移动到下一段结尾?
I'm developing a mobile web, which contents come from a foreign XML, and i'm having trouble with tags. They're coming with style attributes, which I think would be easy to erase using preg_replace in php before showing the contents. The problem comes when a img tag is found within a text... something like: "Hel<img .../>lo My name is Alfred<br/>"
. If I just erase the style attribute (generally coming with display:float), the image breaks the text, making it horrible to read.
My solution is: using preg_replace, I "clean" all image tags, BUT then I need to take those tags and place them after the next <br/>
, </p>
, etc. (every final of paragraph tag). I think it will at least make the page more readable and organized.
The problem: don't know how to get every img tag's index, just after I cleaned it, and then find the next end of paragraph to place it there.
Example-->
before:
Hell<img .../>o my name is Alfred.<br/>
<p>I come <img .../>from England</p>
after:
Hello my name is Alfred<br/>
<img .../>
<p>I come from England</p>
<img .../>
Thanks in advance.
EDIT ---
My doubt is: if I found an img tag (<img />
) in text (maybe using preg_replace, because I first needed to find a img tag, verify its attributes and change them if necessary), how do I get the index inside the whole string (by whole string I mean the whole html document read as a string) so I could take the whole tag and move it to the next end of paragraph?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不会从任何 preg_ 函数获得匹配的位置。另一方面,您可以使用 preg_replace_callback 进行替换,然后堆积匹配项以便随后打印它们。
示例:
例如:
将返回 $withoutimg 中的块以及 $imgs 中包含两个 img 标签的数组。
You won't get the position of the match from any preg_ function. On the other hand you can do the replacement with preg_replace_callback and pile up the matches to print them afterwards.
Example:
So for example:
Will return the block in $withoutimg and an array with the two img tags in $imgs.