-1

I have been messing around with Regex for a couple hours now and I'm at an impass. Lets say I have this:

<a href="/link here/faqs"></a><a href="/link/here/contacts"></a><a href="/link here/faqs">

And I want to use PHP preg_replace to match and remove the faqs link so all that is left is the contacts link in the middle. How would I do that? I found out how to make it match <a href and also match /faqs"></a> but the fact that /faqs"></a> is also in the third link then it removes the second link.

And there could be more after that third link so I can't use an end of line or anything to stop the regex from matching more.

So once again, how do I get it to match the first and match the last, but keep the middle in tack? And remember, there could be other links after the last FAQ and there could be more FAQ links after them. But I want to remove all of the FAQs ones.

As a side note, how would it work if I wanted to remove all the FAQs ones and all the ones named Help as well.

HamZa
  • 14,671
  • 11
  • 54
  • 75

1 Answers1

2

Using an XML parser might be an overkill here:

$html = '<a href="/link here/faqs"></a><a href="/link/here/contacts"></a><a href="/link here/faqs">';
$dom = new DomDocument();
$dom->loadHtml($html);

$xpath = new DomXPath($dom);
$links = $xpath->evaluate('//a');

$newHtml = '';

// rebuild html, and leave out any links that contain "faq"
// in the href attribute
foreach($links as $link)
  if(strpos($link->getAttribute('href'), 'faq') === false)
    $newHtml .= $dom->saveXml($link);

print $newHtml;
nice ass
  • 16,471
  • 7
  • 50
  • 89