EmmyS
EmmyS

Reputation: 12138

How to modify this regex to include https?

I have this piece of regex that I'm using to create clickable links from URLs entered into a textarea. I did not write the code and am not sure how to modify it so that it will create links if the text starts with either http or https.

$html = preg_replace('"\b(http://\S+)"', '<a href="$1">$1</a>', stripslashes($rows['body']));

Upvotes: 2

Views: 274

Answers (3)

Blender
Blender

Reputation: 298364

No regex expert, so this might work:

$html = preg_replace('"\b(http://\S+|https://\S+)"', '<a href="$1">$1</a>', stripslashes($rows['body']));

Upvotes: 0

Dirk Diggler
Dirk Diggler

Reputation: 865

Replace

\b(http://\S+)

with:

\b(https?://\S+)

All together:

$html = preg_replace('"\b(https?://\S+)"', '<a href="$1">$1</a>', stripslashes($rows['body']));

Upvotes: 2

davishmcclurg
davishmcclurg

Reputation: 419

Adding a ? to the regex makes the preceding character optional.

$html = preg_replace('"\b(https?://\S+)"', '<a href="$1">$1</a>', stripslashes($rows['body']));

Upvotes: 4

Related Questions