Using preg_replace to remove link but keep anchor text

  • Post author:
  • Post category:Php

To remove links but keep anchor text using PHP and regular expressions, you can use the preg_replace function to match and replace the HTML anchor tags with just their anchor text. Here’s a PHP code snippet that demonstrates how to do this:

<?php
// Sample HTML content with links
$htmlContent = '<p>This is a <a href="https://example.com">sample link</a> and another <a href="https://example2.com">link</a>.</p>';

// Regular expression to match anchor tags and extract the anchor text
$pattern = '/<a\s+[^>]*href\s*=\s*["\']([^"\']+)[^>]*>(.*?)<\/a>/i';

// Replace anchor tags with their anchor text
$replacement = '$2';

// Use preg_replace to perform the replacement
$cleanedContent = preg_replace($pattern, $replacement, $htmlContent);

// Output the cleaned content
echo $cleanedContent;
?>