preg_replace - 将图像包装在href中 - 并保持相同的路径

时间:2015-08-21 15:34:01

标签: php html regex

我正在尝试使用preg_replace和str_replace来包装所有图像,链接与img src完全相同。我到目前为止工作,但它取出了http:和mywebsite.com

腓:

$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输出

<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>

1 个答案:

答案 0 :(得分:1)

那里的_SITE_URL是什么?

这样的事情:

$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']);

给我:

<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>

看起来没错,对吧?