php正则表达式替换HREF属性

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

$newlink = preg_replace('/^<a href="#(.*)" (?:.*?)>(.*)<\/a>/is', '', $link);

I want replace these links which as aa 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.

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. maybe this looks ugly, but it work :)

$newlink = preg_replace('/(<a href=")#.*?(<\/a>)/is', '', $link);

Let me start by saying that using regular expressions for parsing/modifying HTML documents can be the wrong approach. I'd encourage you to check out DOM Document if you're doing this for any other modifications.

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. Which may be a poor assumption.

If you want to replace only the href's value, you'll need to use assertions to match it without matching anything else. This regex will only match the URL:

/(?<=<a href=")#.*?(?=")/

It's remove only href attribute from html

echo preg_replace('/(<[^>]+) href=".*?"/i', '$1', $content);