How can regular expressions be used to extract a URL from a string in PHP?
Regular expressions can be used to extract a URL from a string in PHP by defining a pattern that matches a typical URL format. The preg_match function can then be used to search the string for this pattern and extract the URL. By specifying the correct regular expression pattern, we can effectively extract URLs from strings in PHP.
$string = "Visit our website at https://www.example.com for more information.";
$pattern = '/https?:\/\/(www\.)?[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,}/';
if (preg_match($pattern, $string, $matches)) {
$url = $matches[0];
echo "Extracted URL: " . $url;
} else {
echo "No URL found in the string.";
}