Wellenbrecher
Wellenbrecher

Reputation: 179

regex matching links without <a> 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 </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.

Upvotes: 8

Views: 4612

Answers (3)

sMyles
sMyles

Reputation: 2666

Here's some PHP code I combined (from answers on here) for a function to do this for emails and URLs:

function replace_links( $content ){
    $content = preg_replace('"<a[^>]+>.+?</a>(*SKIP)(*FAIL)|\b(?:https?)://\S+"', '<a href="$0">$0</a>', $content);
    $content = preg_replace('"<a[^>]+>.+?</a>(*SKIP)(*FAIL)|\b(\S+@\S+\.\S+)\S+"', '<a href="mailto:$0">$0</a>', $content);
    return $content;
}

Demo: https://glot.io/snippets/g6nwd6amyo

Most Updated: https://gist.github.com/tripflex/0cc930c2afe5f4c73f2aed61cedf95d0

Upvotes: 3

Valerij
Valerij

Reputation: 27738

You need to add lookarounds to your regex c.f.:

Upvotes: 1

zx81
zx81

Reputation: 41838

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

Upvotes: 16

Related Questions