Home >Backend Development >PHP Tutorial >Regular expression - PHP regular batch replacement of src in Img question?

Regular expression - PHP regular batch replacement of src in Img question?

WBOY
WBOYOriginal
2016-08-22 11:45:371613browse

1. A description content, in the form of:
<p><img src="file:///C:/Users/Administrator/Desktop/test/data/5201608091357/contentPic/ linen skirt 16/1643805e -1.jpg" /><br /><img src="file:///C:/Users/Administrator/Desktop/test/data/5201608091357/contentPic/ linen skirt 16/1643805e-2 .jpg" /><br /><img src="file:///C:/Users/Administrator/Desktop/test/data/5201608091357/contentPic/ linen skirt 16/1643805e-3.jpg " /><br />

2. Now my requirement is to batch replace the image paths in src. I can change the path to /upload/img/. How do I write the regular change?

Reply content:

1. A description content, in the form of:
<p><img src="file:///C:/Users/Administrator/Desktop/test/data/5201608091357/contentPic/ linen skirt 16/1643805e -1.jpg" /><br /><img src="file:///C:/Users/Administrator/Desktop/test/data/5201608091357/contentPic/ linen skirt 16/1643805e-2 .jpg" /><br /><img src="file:///C:/Users/Administrator/Desktop/test/data/5201608091357/contentPic/ linen skirt 16/1643805e-3.jpg " /><br />

2. Now my requirement is to batch replace the image paths in src. I can change the path to /upload/img/. How do I write the regular change?

str_replace('file:///C:/Users/Administrator/Desktop/test/data/5201608091357/contentPic/ linen skirt 16/','/upload/img/',$str)

1. Because your prefix is ​​fixed, it is actually more efficient to use str_replace.
2. If it is not fixed, you can refer to the following method preg_replace_callback
3. When debugging, remember to view the source code.

<code><?php
    $str = '<p><img src="file:///C:/Users/Administrator/Desktop/测试/data/5201608091357/contentPic/麻短裙16/1643805e-1.jpg" /><br /><img src="file:///C:/Users/Administrator/Desktop/测试/data/5201608091357/contentPic/麻短裙16/1643805e-2.jpg" /><br /><img src="file:///C:/Users/Administrator/Desktop/测试/data/5201608091357/contentPic/麻短裙16/1643805e-3.jpg" /><br />';

    echo $str;

    $pregRule = "/file:\/\/\/C:\/Users\/Administrator\/Desktop\/测试\/data\/5201608091357\/contentPic\//";

    $result = preg_replace_callback($pregRule, function(){
        return "/upload/img/";
    }, $str);
    echo $result;</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn