如何删除preg_replace();??

时间:2011-07-21 15:01:52

标签: php preg-replace

我不知道如何解释这个,所以我会在我的代码上显示它。

<a href="link.php">First</a> and 
<a href="link.php" class="delete">Second</a> and 
<a href="link.php">Third</a>

如何删除开放<a href="link.php" class="delete">并关闭</a>但不删除其余内容?

我要求preg_replace();并且我不是在寻找DomDocument或其他方法来做到这一点。我只是想在preg_replace();

上看一些例子

如何实现?

5 个答案:

答案 0 :(得分:6)

只选择您要保留的群组:

$pattern = '~(<a href="[^"]*" class="delete">)([^<]*)(</a>)~';
//                   1                           2      3
$result = preg_replace($pattern, '$2', $subject);

您可以在preg_replace manual page找到更多示例。

答案 1 :(得分:4)

由于您在评论中要求我显示执行此操作的任何方法,here it is

$html =<<<HTML
<a href="link.php">First</a> and 
<a href="link.php" class="delete">Second</a> and 
<a href="link.php">Third</a>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$elems = $xpath->query("//a[@class='delete']");
foreach ($elems as $elem) {
    $elem->parentNode->removeChild($elem);
}

echo $dom->saveHTML();

请注意,即使您只解析了一个片段,saveHTML()也会保存完整的文档。

从PHP 5.3.6开始,你可以添加一个$node参数来指定它应该返回的片段 - 像$xpath->query("/*/body")[0]这样的工作。

答案 2 :(得分:2)

$pattern = '/<a (.*?)href=[\"\'](.*?)\/\/(.*?)[\"\'](.*?)>(.*?)<\/a>/i';
$new_content = preg_replace($pattern, '$5', $content);

答案 3 :(得分:1)

$pattern = '/<a[^<>]*?class="delete"[^<>]*?>(.*?)<\/a>/';

$test = '<a href="link.php">First</a> and <a href="url2.html" class="delete">Second</a> and <a href="link.php">Third</a>';
echo preg_replace($pattern, '$1', $test)."\n";

$test = '<a href="link.php">First</a> and <a href="url2.html"><b class="delete">seriously</b></a> and <a href="link.php">Third</a>';
echo preg_replace($pattern, '$1', $test)."\n";

$test = '<a href="link.php">First</a> and <a href="url2.html" class="delete"><b class="delete">seriously</b></a> and <a href="link.php">Third</a>';
echo preg_replace($pattern, '$1', $test)."\n";

$test = '<a href="link.php">First</a> and <a  class="delete" href="url2.html">Second</a> and <a href="link.php">Third</a>';
echo preg_replace($pattern, '$1', $test)."\n";

答案 4 :(得分:0)

preg_replace('@<a href="[^"]+" class="delete">(.+?)</a>@', '$1', $html_string);

重要的是要了解这不是理想的解决方案。首先,它需要以完全格式标记。其次,如果有一个嵌套的锚标签(虽然不太可能),这将失败。这些是正则表达式不应该用于解析/操作HTML的众多原因之一。