Wednesday 25 December 2019

php - regex matching links without tag



(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 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           http://www.stackoverflow.com     asdasas
adasdasahttp://www.stackoverflow.com/something asdas


Why do I need this?: I want every link to be clickable even if it isn't between anchor tags.



Answer



With all the disclaimers about using regex to parse html, if you want to use regex for this task, this will work:



$regex="~(*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 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




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...