【问题标题】:preg_replace syntax (img src) and keeping part of the URLpreg_replace 语法 (img src) 并保留部分 URL
【发布时间】:2016-09-25 06:40:33
【问题描述】:

我正在尝试做类似于preg_replace syntax (img src) 的事情,但我不想删除 SRC 属性中的所有内容。

src="http://www.bob.com/co/02/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg"

我只想替换 http://www0.bob.com/co/02/。它可能会有所不同。

所以我要做的是替换图像标签中src="/wp-content/ 之间的内容。

我该怎么办?

这是我试过的代码:

$content = preg_replace('!(?<=src\=\").+(?=\"(\s|\/\>))!', 'http://alex.com/wp-content/', $content); 

【问题讨论】:

    标签: php html regex preg-replace


    【解决方案1】:

    你可以使用,

    $str = 'src="http://www.bob.com/co/02/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg"'; 
    
    preg_replace("/(src=\")(.*)(\/wp-content)/", "$1http://example.com$3", $str);
    

    哪个会返回,

    src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg"
    

    贪婪/非贪婪

    关于non-greedy 的评论意味着您可以使用(.*?) 而不是使用(.*)。你让它不贪婪的原因是因为(.*) 会尽可能多地匹配,例如,如果你的字符串包含两个图像链接:

    $str = '<img src="http://www.bob.com/co/02/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" /> <img src="http://www.bob.com/co/02/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" />'; 
    

    然后,正则表达式中的(.*)会匹配从第一个“http://...”一直到第二个“/wp-content”的所有内容,

    print_r(preg_replace("/(src=\")(.*)(\/wp-content)/", "$1http://example.com$3", $str));
                                    ^^
    

    这将返回&lt;img src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" /&gt;

    使用非贪婪捕获会产生这个结果,

    print_r(preg_replace("/(src=\")(.*?)(\/wp-content)/", "$1http://example.com$3", $str));
                                    ^^^ 
    <img src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" /> <img src="http://example.com/wp-content/uploads/2014/07/david_hasselhoff_at_the_dome_5.jpg" />
    

    【讨论】:

    • 我不确定我是否关注。
    【解决方案2】:

    你可以使用这个正则表达式来获取内容直到 wp-content:

    src="(.*)\/wp-content
    

    Working demo

    比赛信息

    MATCH 1
    1.  [5-29]  `http://www.bob.com/co/02`
    MATCH 2
    1.  [98-113]    `http://alex.com`
    

    【讨论】:

    • @M42 感谢您的建议,但看到 OP 已将问题标记为已解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多