Extract URL's from a string using PHP

Extract URL's from a string using PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Extracting URLs from Text: Moving Beyond Simple Splits

When you need to parse a block of text to find embedded web addresses, the instinctive reaction is often to grab explode(). However, relying on string delimiters like commas or periods for URL extraction is a fragile approach. As you likely know, a URL can contain a comma within its query parameters or a period within a domain subdomain. If your input string looks like "Check out https://example.com/page, it's great.", splitting by comma will break the first URL into fragments. This naive strategy fails immediately because it assumes a rigid structure that the web does not follow.

To handle this robustly, you need a method that understands the pattern of a Uniform Resource Locator rather than just guessing where one ends and another begins. The most reliable way to achieve this in PHP is by leveraging regular expressions. Regular expressions provide the logic necessary to match the specific character sequences that constitute valid URLs, ignoring the surrounding text regardless of punctuation.

You can use preg_match_all() to scan a string and capture all occurrences. This function returns an array of matches, which you can then iterate over or cast directly into a standard PHP array using array_values(). The core challenge lies in constructing a regex pattern that is permissive enough to catch various URL formats but strict enough to avoid false positives on random text like "I love my .gov site" appearing mid-sentence.

A common baseline pattern looks something like this:
#https?://[^\s<>"{}|\\^[]]+#`

This regex targets the http:// or https:// protocol and then matches any character that is not whitespace, angle brackets, quotes, or other special characters. While effective for many cases, it requires careful tuning. For instance, if your source text contains HTML tags like <a href="...">, you might want to capture those as well. You can extend the pattern to include http alongside https, or even allow for bare domain names that start with a number (like "123example.com") by adjusting the initial character class.

Here is how you might implement this in a function:

function extractUrls(string $text): array {
    // Pattern looks for http or https schemes followed by non-whitespace chars
    $pattern = '#https?://[^\s<>"{}|\\^`\[\]]+#i';
    
    preg_match_all($pattern, $text, $matches);
    
    return $matches[0] ?? [];
}

$text = "Visit https://laravelcompany.com for resources or check http://test-site.org/page,123.";
$urls = extractUrls($text);
// Output: ["https://laravelcompany.com", "http://test-site.org/page,123."]

In this example, the comma inside the second URL is preserved correctly because the regex engine treats it as a valid character within the match until it hits the space or invalid delimiter. This demonstrates why explode() is insufficient; it splits at the delimiter regardless of context, whereas regex respects the boundaries of the protocol definition.

There are inherent trade-offs to consider when writing these patterns. A highly permissive regex will catch more URLs but risks matching gibberish if you don't validate the scheme or domain structure. Conversely, a strict RFC-compliant pattern might reject valid short URLs or those with unusual TLDs. For most application logic, a balance is struck by focusing on the presence of the protocol prefix and ensuring the string doesn't terminate at common whitespace characters.

If you are working within the Laravel ecosystem, you might find that building a custom regex is unnecessary for high-level needs. The Illuminate\Support\Str facade provides helper methods, but they generally lack a dedicated "extract URLs" function out of the box. However, you can easily integrate this logic into your service layer or use it directly in controllers when processing user-generated content.

Ultimately, the decision to use regex over string functions boils down to the complexity of the data you are parsing. If your input is guaranteed to be clean with clear delimiters, simple splits work. But in the real world, where URLs sit amidst varied punctuation and spacing, regex remains the standard tool for reliable extraction.

Our network