Are there any best practices for parsing and extracting specific elements, like links, from a string in PHP?

When parsing and extracting specific elements, like links, from a string in PHP, a common approach is to use regular expressions. Regular expressions allow you to define patterns to match specific elements within a string. You can use functions like preg_match_all() to extract all occurrences of a pattern, such as links, from the string.

// Sample string containing links
$string = "Visit our website at <a href='https://www.example.com'>Example</a> or check out our blog at <a href='https://www.example.com/blog'>Blog</a>";

// Regular expression pattern to match links
$pattern = '/<a\s(?:[^>]*)href=(["\'])(.*?)\1/';

// Extract links from the string
preg_match_all($pattern, $string, $matches);

// Output the extracted links
foreach ($matches[2] as $link) {
    echo $link . "\n";
}