如何使用 preg_replace(); 删除链接?
我不确定如何解释这一点,所以我将在我的代码中显示它。
<a href="link.php">First</a> and
<a href="link.php" class="delete">Second</a> and
<a href="link.php">Third</a>
如何删除打开的 并关闭
但不删除其余部分?
我要求 preg_replace();
并且我不是在寻找 DomDocument 或其他方法来执行此操作。我只想看一下 preg_replace();
的示例,
它是如何实现的?
I'm not sure how to explain this, so I'll show it on my code.
<a href="link.php">First</a> and
<a href="link.php" class="delete">Second</a> and
<a href="link.php">Third</a>
how can I delete opening <a href="link.php" class="delete">
and closing </a>
but not the rest?
I'm asking for preg_replace();
and I'm not looking for DomDocument or others methods to do it. I just want to see example on preg_replace();
how is it achievable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
仅选择您想要保留的组:
您可以在
preg_replace 上找到更多示例
手册页。Only pick the groups you want to preserve:
You find more examples on the
preg_replace
manual page.既然您在评论中要求我展示执行此操作的任何方法,这里就是。
请注意,即使您只解析了一个片段,
saveHTML()
也会保存完整的文档。从 PHP 5.3.6 开始,您可以添加
$node
参数来指定它应返回的片段 - 类似于$xpath->query("/*/body")[0]
会起作用。Since you asked me in the comments to show any method of doing this, here it is.
Note that
saveHTML()
saves a complete document even if you only parsed a fragment.As of PHP 5.3.6 you can add a
$node
parameter to specify the fragment it should return - something like$xpath->query("/*/body")[0]
would work.重要的是要了解这不是一个理想的解决方案。首先,它需要这种精确格式的标记。其次,如果存在嵌套的锚标记(尽管不太可能),那么这将会失败。这些是正则表达式不应用于解析/操作 HTML 的众多原因中的一部分。
It is important to understand this is not an ideal solution. First, it requires markup in this exact format. Second, if there were, say, a nested anchor tag (albeit unlikely) this would fail. These are some of the many reasons why Regular Expressions should not be used for parsing/manipulating HTML.