0

I'm trying to use preg_replace and str_replace to wrap all images in with the link being exactly the same as the img src. I have it working so far but it takes out http: and mywebsite.com

Php:

$article_row['copy'] = preg_replace('/(<img [^>]*src="([^"]*)"[^>]*>)/i', '<a href="$2">$1</a>',    $article_row['copy']);

$article_row['copy'] = str_replace('src="/', 'style="float:none; width:100%; clear:both; display:block; margin-bottom:10px; margin-top:10px; height:auto !important; " src="' . _SITE_URL, $article_row['copy']);

HTML output

<a href=\"\/ckfinder\/userfiles\/files\/picture.PNG\"><img alt=\"\" height=\"889\" style=\"float:none; width:100%; clear:both; display:block; margin-bottom:10px; margin-top:10px; height:auto !important; \" src=\"http:\/\/mywebsite.com\/ckfinder\/userfiles\/files\/picture.PNG\" width=\"500\" \/><\/a>
Rob88991
  • 153
  • 14
  • 1
    could you please provide original value of $article_row['copy'] to test on your example. – justtry Aug 21 '15 at 16:03
  • You are probably better off using a parser. http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php – chris85 Aug 21 '15 at 16:07

1 Answers1

2

What is _SITE_URL there?

Something like this:

$article_row['copy'] = '<img src="https://www.gravatar.com/avatar/1a7926d223f025242d8ec5b120cc3e68?s=32&d=identicon&r=PG&f=1" title="" alt="" border="0" width="728" height="90">';
$article_row['copy'] = preg_replace('/(<img [^>]*src="([^"]*)"[^>]*>)/i', '<a href="$2">$1</a>',    $article_row['copy']);

$article_row['copy'] = str_replace('src="/', 'style="float:none; width:100%; clear:both; display:block; margin-bottom:10px; margin-top:10px; height:auto !important; " src="' , $article_row['copy']);

Gives Me:

<a href="https://www.gravatar.com/avatar/1a7926d223f025242d8ec5b120cc3e68?s=32&d=identicon&r=PG&f=1"><img src="https://www.gravatar.com/avatar/1a7926d223f025242d8ec5b120cc3e68?s=32&d=identicon&r=PG&f=1" title="" alt="" border="0" width="728" height="90"></a>

Looks correct, right?

justtry
  • 639
  • 4
  • 8