Reputation: 2609
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.
Upvotes: 3
Views: 4814
Reputation: 1324
use /(<a.*?href=([\'"]))(.*?)(\2.*?>)/i
regex
<?php
$oldLink = '<a href="http://test.com">click this link</a>';
$res = "http://stackoverflow.com";
echo $newLink = preg_replace('/(<a.*?href=([\'"]))(.*?)(\2.*?>)/i', '$1'.$res.'$2', $oldLink);
?>
if you wants to test this regex, then you can here https://regex101.com/r/mT1sVK/1
Upvotes: 0
Reputation: 1497
It's remove only href attribute from html
echo preg_replace('/(<[^>]+) href=".*?"/i', '$1', $content);
Upvotes: 1
Reputation: 2609
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);
Upvotes: 0
Reputation: 520
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=")#.*?(?=")/
Upvotes: 0
Reputation: 72971
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.
Upvotes: 3