1

I want to remove all links which matched this domain vnexpress.net in href attribute. This is a link example:

<a href="http://vnexpress.net/whatever">whatever</a>

This is my code:

$contents = preg_replace('/<a\s*href=\"*vnexpress*\"\s(.*)>(.*)<\/a>/', '', $data->content);

Please help me! Thank you so much!.

6
  • What regex do you have so far, and what error is it giving? Commented Jan 16, 2015 at 4:41
  • 1
    href="\K[^"]*\bvnexpress\.net[^"]* Commented Jan 16, 2015 at 4:43
  • @AvinashRaj i tried to use your code but it was not working. Commented Jan 16, 2015 at 4:51
  • try this '~<a\s*href="[^"]*?\bvnexpress.net\b[^"]*"\s*>([^<>]*)<\/a>~' Commented Jan 16, 2015 at 4:53
  • @AvinashRaj it's still not working. The links were still existed. Commented Jan 16, 2015 at 5:04

2 Answers 2

2

You've asked for a regular expression here, but it's not the right tool for parsing HTML.

$doc = new DOMDocument;
$doc->loadHTML($html); // load the html

$xpath = new DOMXPath($doc);
$links = $xpath->query("//a[contains(@href, 'vnexpress.net')]");

foreach ($links as $link) {
   $link->parentNode->removeChild($link);
}

echo $doc->saveHTML();
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

$re = "/<a[^>]+href=\"[^\"]*vnexpress.net[^>]+>(.*)<\\/a>/m";
$str = "<a id=\"\" href=\"http://vnexpress.net/whatever\">whatever <b>sss</b> </a>\n<a id=\"\" href=\"http://new.net/whatever\">whatever</a>\n";
$subst = "$1";

$result = preg_replace($re, $subst, $str);

Live demo

4 Comments

@Duy Nguyen If this answer works for your condition, then you may accept this answer..
This pattern will fail (because of the use of .*) in this kind of situation: <a href="">text</a><a href="http://vnexpress.net/whatever">text</a>
@CasimiretHippolyte can you improve it? and can you explain more (.*), please. I am new in regex, so i don't understand what it mean.
@CasimiretHippolyte Yes, it will be /<a[^>]+href=\"[^\"]*vnexpress.net[^>]+>(.*)<\\/a>/m.. thanks a lot..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.