[英]replacing all image src tags in HTML text
I'm trying to make a simple php script to find all src attributes from all images in a html text and then replace all found srcs with some text after making some conditional changes. 我正在尝试制作一个简单的php脚本,以从html文本中的所有图像中找到所有src属性,然后在进行一些条件更改后用某些文本替换所有找到的srcs。
Something like this: 像这样:
@preg_match_all('/<img\s src="([a-zA-Z0-9\.;:\/\?&=_|\r|\n]{1,})"/isxmU', $body, $images);
now i've all srcs into the $images variable, now i make: 现在我已经将所有srcs都放入$ images变量中,现在我做了:
foreach ($images as $img) {
..my changes here..
}
and now... how can i restore the changed srcs to the $body variable again?? 现在...我该如何再次将更改后的srcs恢复到$ body变量?
many thanks in advance, 提前谢谢了,
You should look into preg_replace_callback()
, which will allow you to postprocess each match however you like, using a callback function. 您应该查看
preg_replace_callback()
,这将允许您使用回调函数对每个匹配项进行后处理。 (You would use it instead of your preg_match_all()
, not in addition to it.) (您可以使用它代替您的
preg_match_all()
,而不是除此之外。)
改用HTML DOM解析器,更容易使用和维护http://simplehtmldom.sourceforge.net/
I asked a question yesterday about a good interface for modifying and traversing HTML files. 昨天我问了一个有关修改和遍历HTML文件的界面的问题 。 You may be interested in this:
您可能对此感兴趣:
jQuery port to PHP jQuery移植到PHP
This may be a good alternative if you are already familiar with jQuery's API. 如果您已经熟悉jQuery的API,这可能是一个不错的选择。
A non-validating parser may be even better if you need to work with badly formed HTML. 如果您需要使用格式错误的HTML,则非验证解析器可能会更好。
http://pear.php.net/package/XML_HTMLSax3 http://pear.php.net/package/XML_HTMLSax3
I think the easiest answer you're looking for is to do a str_replace. 我认为您正在寻找的最简单答案是执行str_replace。
foreach ($images as $img) {
..my changes here..
$body = str_replace($original_string, $modified_string, $output_body);
}
Don't what you want is to use preg_replace
? 您不想要使用
preg_replace
吗? With the e
modifier the replacement text is eval
'd so you can have a function that do on the text-to-be-replaced the same thing that you would have done in your foreach
loop. 使用
e
修饰符,替换文本为eval
,因此您可以使用一个函数对要替换的文本执行与在foreach
循环中相同的操作。
EDIT: preg_replace_callback
is cleaner than using the e
modifier with preg_replace
, didn't thought of that while writing my anser, so chaos answer is better. 编辑:
preg_replace_callback
比使用清洁e
修饰符preg_replace
,一边写我的雁没想到的是,如此混乱的回答更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.