(http([s]?):\/\/?)(([a-zA-Z0-9]+(\.?))+)([a-zA-Z0-9]+((\.[a-zA-Z]{2,5}){1,2})((\/[a-zA-Z0-9\?&=_\-\~:/?#[\]@!\$&'()\*\+,;]*)*)((\.[a-zA-Z]{2,5}){0,2}))
This is my regex which is working well for matching the links in the string. But I don't want it to select every link. If a link has ">
before it, or </a>
after it, that link shouldn't be mathced. How can it be done?
These should be matched:
adasdas http://www.stackoverflow.com asdasas
adasdasahttp://www.stackoverflow.com/something asdas
These should NOT be matched:
adasdas<a href="somelink"> http://www.stackoverflow.com </a>asdasas
adasdasa<a href="somelink">http://www.stackoverflow.com/something</a> asdas
Why do I need this?: I want every link to be clickable even if it isn't between anchor tags.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
@:%_\+~#= , to match the domain/sub domain name.
An empty regular expression matches everything.
Example : [^abc] will match any character except a,b,c . [first-last] – Character range: Matches any single character in the range from first to last.
With all the disclaimers about using regex to parse html, if you want to use regex for this task, this will work:
$regex="~<a.*?</a>(*SKIP)(*F)|http://\S+~";
See the demo.
This problem is a classic case of the technique explained in this question to "regex-match a pattern, excluding..."
The left side of the alternation |
matches complete <a ...tags </a>
then deliberately fails, after which the engine skips to the next position in the string. The right side matches the urls, and we know they are the right ones because they were not matched by the expression on the left.
The url regex I put on the right and can be refined, just use whatever suits your needs.
Reference
You need to add lookaround
s to your regex c.f.:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With