replacing all image src tags in HTML text

让人想犯罪 __ 提交于 2019-12-08 06:35:44

问题


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.

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:

foreach ($images as $img) {
    ..my changes here..
}

and now... how can i restore the changed srcs to the $body variable again??

many thanks in advance,


回答1:


Use a HTML DOM parser instead, much easier to use and maintain http://simplehtmldom.sourceforge.net/




回答2:


You should look into preg_replace_callback(), which will allow you to postprocess each match however you like, using a callback function. (You would use it instead of your preg_match_all(), not in addition to it.)




回答3:


I asked a question yesterday about a good interface for modifying and traversing HTML files. You may be interested in this:

jQuery port to PHP

This may be a good alternative if you are already familiar with jQuery's API.




回答4:


A non-validating parser may be even better if you need to work with badly formed HTML.

http://pear.php.net/package/XML_HTMLSax3




回答5:


I think the easiest answer you're looking for is to do a str_replace.

foreach ($images as $img) {
    ..my changes here..
    $body = str_replace($original_string, $modified_string, $output_body);
}



回答6:


Don't what you want is to use 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.

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.



来源:https://stackoverflow.com/questions/1363065/replacing-all-image-src-tags-in-html-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!