【问题标题】:remove img tag src is a url using preg_replace删除 img 标签 src 是使用 preg_replace 的 url
【发布时间】:2012-11-02 17:23:05
【问题描述】:

您好,我想删除一个 img 标签,它的 src 是使用 preg_replace 的内容中的一个 url

例如。

    $content = "<center><img src="http://example.net/wp-content/uploads/2012/10/cell-degeneration-contn.jpg" alt="" title="cell-degeneration-contn" width="950" height="272" class="alignnone size-full wp-image-100" /></center><h2>A first-in-class approach to stop & reverse </h2>";

所以输出将是:

    $content="<center></center><h2>A first-in-class approach to stop & reverse </h2>";

但如果可能的话,最好的输出是:

    $content="A first-in-class approach to stop & reverse ";

【问题讨论】:

  • 是否可以使用 preg_replace?
  • 欢迎堆栈溢出。正如 Marc B 指出的那样,正则表达式似乎不是操作 html 文本的方式;只是澄清你是否真的需要 preg_replace

标签: php regex html


【解决方案1】:

preg_match_all() 可以在这里工作,但对于 HTML,它并不是最有效的。

$content = '<center><img src="http://example.net/wp-content/uploads/2012/10/cell-degeneration-contn.jpg" alt="" title="cell-degeneration-contn" width="950" height="272" class="alignnone size-full wp-image-100" /></center><h2>A first-in-class approach to stop & reverse </h2>';

preg_match("/<h2>(.*)<\/h2>/",$content,$matches);
$output = $matches[1];
echo $output;

最简单的方法就是使用strip_tags()

$output = strip_tags($content);
echo $output;

【讨论】:

  • 为什么是 preg_match_all 而不是 preg_match ? :-??
【解决方案2】:

你可以这样做:

    $content = "<center><img src='http://example.net/wp-content/uploads/2012/10/cell-degeneration-contn.jpg' alt='' title='cell-degeneration-contn' width='950' height='272' class='alignnone size-full wp-image-100' /></center><h2>A first-in-class approach to stop & reverse </h2>'";
    preg_match("/<h2>(.+)<\/h2>/", $content, $matches);  
    $match = $matches[1];
    echo $match;

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 2012-01-10
    • 1970-01-01
    相关资源
    最近更新 更多