Your current code fails to match naked URLs, which lack the "http://" prefix. To address this, consider adopting a comprehensive regular expression:
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
This enhanced expression includes the following features:
For those who do not require the HTTP protocol in their matches, an alternative expression is available:
[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
To demonstrate the functionality of these expressions, check out the online testing tools at http://regexr.com?37i6s (for the first expression) or http://regexr.com/3e6m0 (for the less restrictive expression).
Here's an example JavaScript implementation using the more comprehensive regular expression:
const expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi; const regex = new RegExp(expression); const t = 'www.google.com'; if (t.match(regex)) { alert("Successful match"); } else { alert("No match"); }
The above is the detailed content of How Can I Use Regular Expressions to Detect URLs, Including Naked URLs?. For more information, please follow other related articles on the PHP Chinese website!