如何将中的空格替换为%20标签
我想替换 html 文本的图像标签中的所有空格。
示例:
<img src="photo 1.jpg" />
我
<img src="photo%201.jpg"/>
没有找到 preg_replace 的灵魂,但它可能是一个简单的正则表达式行。 谢谢!
编辑:抱歉大家,我的描述不是很清楚。所以,我有一个完整的 html 页面,我只想替换 img 标签内的内容。我不能在这里使用 urlencode,因为它也对其他内容进行编码。
I would like to replace all spaces in the image tags of a html text.
Example:
<img src="photo 1.jpg" />
to
<img src="photo%201.jpg"/>
I didn't find a soultion with preg_replace, but it may be a simple regexp line.
Thanks!
Edit: Sorry guys, my description was not very clear. So, I have a full html page and I only want to replace inside the img tags. I can't use urlencode here as it encodes the other stuff as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
编辑
我可能错过了这一点,如果你没有扫描已经写好的 HTML,这可能不适合你。这是为了如果您出于某种原因要废弃它。我将其保留为纯粹的怀旧之情,因为它可以帮助其他想要刮擦和更换的人。抱歉造成混乱。
既然您知道标签和属性,我建议您查看 PHP DOM 来执行此操作。正则表达式可以做到这一点,但考虑到您正在查看的上下文,DOM 会是首选,并且可能更容易/更可靠。这将扫描生成的 HTML 并允许您使用 rawurlencode() 可以将空格转换为%20。
处理我的小测试文件,只是一个如何完成它的示例:)
EDIT
I may have missed the point, if you are not scanning over already written out HTML, this probably is not for you. This is for if you were scrapping it for whatever reason. I am leaving it up for pure nostalgia as it could help someone else who wants to scrape and replace. Sorry for the confusion.
Since you know the tags and the attribute, I would suggest looking into the PHP DOM to do this. Regex can do it, but the DOM would be preferred and perhaps bit easier / more reliable, given the context you are looking at. This will scan the generated HTML and allow you to replace items inside of attributes (in this case
src
) that with using the rawurlencode() you can get the spaces converted to %20.Worked on my small test file, just an example of how it could be done :)
空格由 url 中的 %20 表示,但您可能希望将其他字符转换为其他图像,因此您应该使用通用 urlencode 函数,而不是使用 OP 中所述的“简单正则表达式”。
The space is represented by a %20 in the url but there are other chars that you might want to have converted for other images so you should use the general urlencode function instead of using a "simple regex" as stated in the OP.
这就是你所需要的
rawurlencode();
php.net/rawurlencode
this is what you need
rawurlencode();
php.net/rawurlencode
嘿,
我找到了一个简单的解决方案,使用 preg_replace_callback。我以前从未听说过这个功能,但它很棒。
在这里发布代码:
感谢所有回复。
Hey,
I've found a simple solution, using preg_replace_callback. I've never heard of this function before, but it's great.
Posting the code here:
Thanks for all the replies.
像下面这样的东西可能会起作用:
但是有点难以判断,因为您没有向我们提供任何关于为什么
preg_replace
不起作用、它的输出是什么等的详细信息。Something like the following may work:
But it's a bit hard to tell since you didn't give us any details about why
preg_replace
didn't work, what its output was, etc.