[英]php regular expression to replace HREF attribute
How to use php preg_replace
and regular expression
to remove all the hyperlink which contain <a href="#
. Here is what I write, but it doesn't work如何使用 php
preg_replace
和regular expression
删除所有包含<a href="#
的超链接。这是我写的,但它不起作用
$newlink = preg_replace('/^<a href="#(.*)" (?:.*?)>(.*)<\/a>/is', '', $link);
I want replace these links which as aa anchor mark
我想替换这些作为
anchor mark
的链接
<a href="#part1">go to part1</a>
<a href="#part2">go to part2</a>
<a href="#part3">go to part3</a>
to empty value.为空值。
Let me start by saying that using regular expressions for parsing/modifying HTML documents can be the wrong approach.首先让我说使用正则表达式解析/修改 HTML 文档可能是错误的方法。 I'd encourage you to check out DOM Document if you're doing this for any other modifications.
如果您正在这样做以进行任何其他修改,我鼓励您查看DOM 文档。
With that said, making your expression non-greedy ( .*?
) will probably work.话虽如此,使您的表达不贪婪(
.*?
)可能会起作用。
$newlink = preg_replace('/^<a href="#(.*?)"[^>]+>(.*?)<\/a>/', '', $link);
Note: This also assumes href
is the first attribute in all you anchor tags.注意:这也假设
href
是所有锚标记中的第一个属性。 Which may be a poor assumption.这可能是一个糟糕的假设。
It's remove only href attribute from html它仅从 html 中删除 href 属性
echo preg_replace('/(<[^>]+) href=".*?"/i', '$1', $content);
If you want to replace only the href's value, you'll need to use assertions to match it without matching anything else.如果您只想替换 href 的值,则需要使用断言来匹配它而不匹配其他任何内容。 This regex will only match the URL:
此正则表达式将仅匹配 URL:
/(?<=<a href=")#.*?(?=")/
Thanks two of all, But both of your answer still not work for me.非常感谢两个,但是您的两个答案仍然对我不起作用。
I am not good at regular expression
, I read many documents and write again.我不擅长
regular expression
,我阅读了很多文档并重新编写。 maybe this looks ugly, but it work:)也许这看起来很难看,但它有效:)
$newlink = preg_replace('/(<a href=")#.*?(<\/a>)/is', '', $link);
<?php
$oldLink = '<a href="http://test.com">click this link</a>';
$res = "http://stackoverflow.com";
echo $newLink = preg_replace('/(href=([\'"]))(.+)\2/i', '$1'.$res.'$2', $oldLink);
?>
if you wants to test this regex, then you can here https://regex101.com/r/6vnIy1/1
如果你想测试这个正则表达式,那么你可以在这里
https://regex101.com/r/6vnIy1/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.