PHP

Extract All URLs from Text Using Regex

A PHP code snippet demonstrating how to use regular expressions to efficiently find and extract all valid URLs, including both HTTP/HTTPS links, from a given text or HTML content.

<?php 
function extractUrls($text) { 
    // Regex to match common URL patterns 
    $urlRegex = '/\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/i'; 
    preg_match_all($urlRegex, $text, $matches); 
    return $matches[0]; 
} 

$text = "Visit our website at https://www.example.com or check out http://blog.example.org/latest. Some text without a url. FTP link: ftp://example.net/downloads"; 
$urls = extractUrls($text); 
print_r($urls); 
?>
How it works: This PHP function utilizes `preg_match_all` with a regular expression to find and extract all occurrences of URLs (supporting http, https, and ftp protocols) from a given string. This is useful for content processing, link analysis, or sanitizing user-generated content on the server-side.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs