Detecting URLs Without http:// or www
Your current regex pattern successfully validates strict URL schemas starting with http://. However, relying solely on that prefix often leads to false negatives when users paste shortened links, relative paths, or domain names without the protocol scheme. To capture these variations, you need a pattern that treats the input as an optional scheme followed by the core domain structure.
The logic for detecting whether a string represents a URL should not be binary; it must account for the optional nature of the protocol prefix (http:// vs https://) and the optional presence of the subdomain identifier (www.). A robust regex for this scenario needs to anchor to the start of the string but allow zero or one occurrence of the scheme and domain prefix.
Here is a refined approach using PHP's preg_match. This pattern makes the protocol and the www subdomain optional:
function isValidURL($url) {
// Matches:
// 1. Optional http(s):// scheme
// 2. Optional www. subdomain
// 3. Required domain name (letters, numbers, hyphens)
// 4. Optional TLD (.com, .org, etc.)
// 5. Optional port and path
return preg_match('/^(https?:\/\/)?(www\.)?[a-z0-9.-]+(\.[a-z]{2,})?(:[0-9]+)?(\/.*)?$/i', $url);
}
The key adjustment here is the grouping (https?:\/\/)?. The question mark makes the entire protocol group optional. Without it, a string like example.com fails immediately because the regex expects the forward slashes after http. Similarly, (www\.)? handles the subdomain requirement without forcing it. This allows the function to return true for http://example.com, https://secure.example.com, www.example.com, or even just example.com.
Handling Array Input and Validation Logic
Your original code breaks the input string into an array using explode(" ", $_POST['text']) before iterating. While this works for space-separated inputs, it introduces a significant fragility point: multiple spaces, tabs, or newlines will generate empty strings in your array. When preg_match runs against an empty string, it returns 0 (false), which might be safe, but it creates unnecessary function calls and obscures the actual data processing logic.
A more resilient approach filters out empty values before validation:
$stringToArray = explode(" ", $_POST['text']);
foreach ($stringToArray as $val) {
// Trim whitespace to handle multiple spaces or tabs gracefully
if (trim($val) === '') {
continue;
}
$urlValid = isValidURL(trim($val));
if ($urlValid) {
$_SESSION["messages"][] = "NO URLS ALLOWED!";
header("Location: http://www.domain.com/post/id/" . $_POST['postID']);
exit();
}
}
By adding trim(), you ensure that the regex engine receives a clean string. If the user pastes text with extra spacing, the function skips empty chunks rather than failing silently or matching artifacts of whitespace.
Security and Regex Pitfalls
While this regex covers common URL formats, it is not a silver bullet for security. Regular expressions are notoriously difficult to use correctly when parsing arbitrary input. A pattern that looks valid might still fail on edge cases like internationalized domain names (IDN) or IPv4 addresses embedded in URLs (e.g., http://192.168.1.1/path).
If your application requires strict security, relying solely on a regex to whitelist URLs is risky. It is often better to validate against a known list of allowed domains or use a dedicated URL parsing library that adheres to RFC 3986 standards. If you are building this for a Laravel project, consider using the illuminate/http package utilities which provide robust request validation methods without needing to maintain complex regex patterns manually.
Furthermore, always ensure you are escaping variables correctly if you were to inject them into strings before checking them, though in your specific case, the input comes directly from $_POST. The main vector here is logic: ensuring that a "valid" URL detected by the regex actually points to a resource you intend to allow.
Finally, remember that preg_match returns 1 for a match and 0 for no match. Your conditional logic relies on this integer return value directly, which is efficient but requires careful error handling if the input is malformed in ways the regex doesn't account for.