开发者

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

$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&开发者_高级运维lt;/a>

to empty value.


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.


It's remove only href attribute from html

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. This regex will only match the 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. maybe this looks ugly, but it work :)

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜