What is the purpose of using regular expressions in PHP for extracting URLs?

Regular expressions in PHP can be used to extract URLs from text by defining a pattern that matches the structure of a URL. This can be useful when parsing text to extract specific URLs for further processing or validation. By using regular expressions, we can efficiently search for and extract URLs from a given text input.

$text = "Check out this website: https://www.example.com and also visit http://anotherexample.com";
$pattern = '/(https?:\/\/[^\s]+)/';
preg_match_all($pattern, $text, $matches);

foreach ($matches[0] as $url) {
    echo $url . "\n";
}