Mary.G
Mary.G

Reputation: 41

preg_replace URLs but not images

$title =  $_POST['title'];

$post = stripslashes($_POST['TextArea']);

$link = preg_replace('"(http://www\S+)"','<a href="$1">$1</a>', $post);

echo $link;

After submit my form the above script replace all links inside textarea and the result for images is to be broken.

Is there a way to replace links but not images?

While url works perfect the result for images in browser is

<img src="<a href="http://...myimage.jpg"">http://.../myimage.jpg"</a> height="150" width="150">

enter image description here enter image description here

Thank you

Upvotes: 4

Views: 1363

Answers (2)

bluestart83
bluestart83

Reputation: 337

preg_replace('/(?<!src=[\"\'])(http(s)?:\/\/(www\.)?[\/a-zA-Z0-9%\?\.\-]*)(?=$|<|\s)/','<a href="$1">$1</a>', $text);

This is the correct way because previous solution does not finish url when necessary

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191819

preg_replace('"(?<!src=[\"\'])(http://www\S+)"','<a href="$1">$1</a>', $text)

This will only convert http://www links that are not preceded by src=" or src='.

Upvotes: 4

Related Questions