How can PHP be used to selectively modify links in HTML code, excluding certain areas like textarea fields?

To selectively modify links in HTML code while excluding certain areas like textarea fields, you can use PHP to parse the HTML code, identify the links, and apply modifications only to the desired elements. One way to achieve this is by using PHP's DOMDocument class to load the HTML code, traverse the DOM tree to find links, and manipulate them accordingly. You can exclude textarea fields by checking the node type before applying any modifications.

<?php
$html = '<html><body><a href="https://example.com">Link 1</a><textarea>Text area content</textarea><a href="https://example2.com">Link 2</a></body></html>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$links = $dom->getElementsByTagName('a');

foreach ($links as $link) {
    if ($link->parentNode->tagName !== 'textarea') {
        $link->setAttribute('href', $link->getAttribute('href') . '/modified');
    }
}

$modifiedHtml = $dom->saveHTML();

echo $modifiedHtml;
?>