0

I have the following code:

$string = 'Try to remove the link text from the content <a href="#">links in it</a> Try to remove the link text from the content <a href="#">testme</a> Try to remove the link text from the content';
$string = preg_replace('#(<a.*?>).*?(</a>)#', '$1$2', $string);
$result = preg_replace('/<a href="(.*?)">(.*?)<\/a>/', "\\2", $string);
echo $result; // this will output "I am a lot of text with links in it";

I am looking to merge these preg_replace lines. Please suggest.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Anil Nautiyal
  • 41
  • 1
  • 7
  • First, the output is [`Try to remove the link text from the content Try to remove the link text from the content Try to remove the link text from the content`](https://ideone.com/ouDh3o). Second, did you consider using PHP DOM? Third, could you please explain in a more detailed way what the problem is? Just making code smaller by jeopardizing safety? – Wiktor Stribiżew Jul 15 '15 at 08:43
  • Why are you trying to do this? What's the problem you're trying to solve with the above code? There is most certainly a better way to do this, especially since RegEx [should not be used to parse HTML](http://stackoverflow.com/a/1732454/5086233). – ChristianF Jul 15 '15 at 09:25

1 Answers1

2

You need to use DOM for these tasks. Here is a sample that removes links from this content of yours:

$str = 'Try to remove the link text from the content <a href="#">links in it</a> Try to remove the link text from the content <a href="#">testme</a> Try to remove the link text from the content';
$dom = new DOMDocument;
@$dom->loadHTML($str, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
$xp = new DOMXPath($dom);
$links = $xp->query('//a');
foreach ($links as $link) {
    $link->parentNode->removeChild($link);
 }
echo preg_replace('/^<p>([^<>]*)<\/p>$/', '$1', @$dom->saveHTML());

Since the text node is the only one in the document, the PHP DOM creates a dummy p node to wrap the text, so I am using a preg_replace to remove it. I think it is not your case.

See IDEONE demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563