Skip to content
PHP Logo

How can the PHP code be modified to handle multiple links without replacing the text between them?

When handling multiple links in PHP, you can use a regular expression to match and replace each link individually without replacing the text between them. This can be achieved by using the preg_replace() function with a regex pattern that captures the link and its surrounding text separately.

php
$text = "This is a <a href='https://www.example.com'>link</a> and another <a href='https://www.example2.com'>link</a>.";

$pattern = "/<a\s+(?:[^>]*?\s+)?href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/si";
$replacement = "<a href='$2'>$3</a>";

$modified_text = preg_replace($pattern, $replacement, $text);

echo $modified_text;