Extract URLs from text in PHP

Extract URLs from text in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting URLs from Text in PHP with Regex

You have a string containing arbitrary text mixed with a specific URL, and you need to isolate that link into a separate variable. While preg_match() is indeed the standard tool for this job, constructing the correct pattern requires understanding how HTTP addresses are structured. The goal isn't just to grab any sequence of characters; it's to capture the protocol scheme, the host, and potentially the path without accidentally matching surrounding words like "coll" or punctuation marks.

The core logic relies on defining what makes up a valid URL segment. A URL typically starts with a scheme like http:// or https://. Following that is a domain name, which consists of alphanumeric characters, dots, and hyphens. It ends when it hits whitespace, a closing parenthesis, or a similar delimiter.

Here is a practical implementation using preg_match() to extract the first URL found in your string:

$string = "this is my friend's website http://example.com I think it is coll";

// Define the pattern
// ^ and $ are not used here because we want to find the match within the string, not just at boundaries.
// We use a non-greedy approach or simply stop at whitespace/punctuation.
$pattern = '/https?:\/\/[^\s\)\>]+/i';

if (preg_match($pattern, $string, $matches)) {
    $extractedUrl = $matches[0];
    echo "Found: " . $extractedUrl; 
    // Output: Found: http://example.com
}

The regex pattern /https?:\/\/[^\s\)\>]+/i breaks down as follows. The https? part matches either "http" or "https". The :\/\/ escapes the forward slashes, which are special characters in regex, to match the literal protocol separator. The character class [^\s\)\>] is crucial; it matches any character that is not whitespace (\s), a closing parenthesis ()), or a closing angle bracket (>). This ensures the capture stops exactly before trailing text like "coll" or punctuation marks, preventing false positives where the regex might consume too many characters.

One significant trade-off to consider is handling multiple URLs within a single string. The preg_match() function returns true only after finding the first match and modifies the $matches array accordingly. If you need to extract every link in a paragraph, switching to preg_match_all() is necessary. It populates the array with all occurrences, allowing you to iterate through them easily.

if (preg_match_all($pattern, $string, $matches)) {
    $allUrls = $matches[0];
    foreach ($allUrls as $url) {
        // Process each URL
    }
}

Another common pitfall involves the i modifier. While case-insensitive matching is convenient for domains (like .com vs .COM), you must ensure your logic handles edge cases where the scheme might be mixed in or where protocol-relative URLs (starting with //) appear. For standard extraction from raw text, sticking to explicit schemes like http:// or https:// is safer than relying on generic patterns that might grab internal links without a scheme.

If you are building this logic into a larger Laravel application, you might consider leveraging the framework's built-in tools. While regex is powerful for parsing strings, Laravel provides robust helpers for validation and sanitization. If your goal extends beyond simple extraction to verifying link validity or normalizing them, integrating with a library that handles URL normalization can reduce bugs caused by irregular inputs. However, for straightforward text parsing, the raw preg_match() approach offers maximum control over exactly what gets captured.

Finally, remember that regex patterns are fragile. A slight change in the input format, such as adding query parameters like ?ref=123 or fragments like #section, requires updating the character class to include them if you want to capture the full address. Adjusting the pattern to /https?:\/\/[^\s\)\>]+/i to /https?:\/\/[^\s\)\>\?\#\[]+/i would ensure paths and query strings are included in the result.

Our network