【问题标题】:Change img src from database with regex?使用正则表达式从数据库更改 img src?
【发布时间】:2013-07-17 06:47:32
【问题描述】:

我在数据库中的列内容例如是这样的:

<table border="0" cellspacing="1" cellpadding="1" width="200" align="center">
<tbody>
    <tr>
        <td>
            <a href="http://example.cz/cz/katalog/some_product/">
               <img src="http://example.cz/article/3584/photo/some_product.jpg" />
            </a>
        </td>

        <td>
            <a href="http://example.cz/cz/katalog/some_product2/">
               <img src="http://example.cz/article/3584/photo/some_product2.jpg" />
            </a>
        </td>
   ...

如果我进行 mysql 查询以获取此内容,我需要将图像和 href 标签的来源更改为另一个网站(路径相同),例如:

<table border="0" cellspacing="1" cellpadding="1" width="200" align="center">
<tbody>
    <tr>
        <td>
            <a href="http://anotherWebsite.cz/cz/katalog/some_product/">
               <img src="http://anotherWebsite.cz/article/3584/photo/some_product.jpg" />
            </a>
        </td>

        <td>
            <a href="http://anotherWebsite.cz/cz/katalog/some_product2/">
               <img src="http://anotherWebsite.cz/article/3584/photo/some_product2.jpg" />
            </a>
        </td>
   ...

我试过函数:

    str_replace('example', 'anotherWebsite', $content);

但没有结果。有没有其他方法可以替代它?例如使用正则表达式?如果正则表达式是你能告诉我的方式吗?因为我不擅长正则表达式。真的谢谢。

【问题讨论】:

  • 你做了$content = str_replace('example', 'anotherWebsite', $content);吗?
  • 更安全的是:$content = str_replace('"http://example.cz/', '"http://anotherWebsite.cz/', $content);

标签: php mysql regex replace


【解决方案1】:

按常用术语运行 str_replace 可能会产生意想不到的结果。你可以说更具体

$content = str_replace(array('href="http://example.cz/','src="http://example.cz/'), 
                       array('href="http://anotherWebsite.cz/','src="http://anotherWebsite.cz/'), 
                       $content);

这样它只替换作为 href 属性的 src 一部分的值。

您可能还需要为 ' vs " 添加规则。

【讨论】:

    【解决方案2】:

    str_replace 应该可以工作。您确定为变量分配了新值吗?

    $content = str_replace('example', 'anotherWebsite', $content);
    

    【讨论】:

    • 天哪,真可惜。大概我还在睡觉。感谢您的快速回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    相关资源
    最近更新 更多