php - 在文本中找到图像链接并转换为链接

时间:2012-05-06 16:13:03

标签: php image hyperlink

我想在我的网站上实现以下功能。当用户发布某些内容时,他还可以包含一个链接,该链接是图片的链接。想象一下,用户发布了这样的内容:

Hello look at this awesome picture. It is hilarious isn't it?
http://www.google.com/image.jpg

然后该文本应转换为:

Hello look at this awesome picture. It is hilarious isn't it?
<a target="_blank" href="http://www.google.com/image.jpg">
    <img src="http://www.google.com/image.jpg" alt=""/>
</a> 

所以我需要一些php脚本在文本中搜索链接,如果找到链接,检查它是否链接到图片。它还需要能够识别不以http开头的链接,以及以https开头的链接。

你会怎么做?

非常感谢:)

丹尼斯

2 个答案:

答案 0 :(得分:2)

这两个链接的组合如何:

best way to determine if a URL is an image in PHP

PHP Regular Expression Text URL to HTML Link

$url="http://google.com/image.jpg";

function isImage( $url ){
  $pos = strrpos( $url, ".");
    if ($pos === false)
      return false;
    $ext = strtolower(trim(substr( $url, $pos)));
    $imgExts = array(".gif", ".jpg", ".jpeg", ".png", ".tiff", ".tif"); // this is far from complete but that's always going to be the case...
    if ( in_array($ext, $imgExts) )
      return true;
return false;
}

$test=isImage($url);
if($test){
  $pattern = '/((?:[\w\d]+\:\/\/)?(?:[\w\-\d]+\.)+[\w\-\d]+(?:\/[\w\-\d]+)*(?:\/|\.[\w\-\d]+)?(?:\?[\w\-\d]+\=[\w\-\d]+\&?)?(?:\#[\w\-\d]*)?)/';
  $replace = '<a href="$1">$1</a>';
  $msg = preg_replace( $pattern , $replace , $msg );
  return stripslashes( utf8_encode( $msg ) );
}

答案 1 :(得分:0)

这是此的工作代码:

<?php

$sad222="somthing text bla bla bla ...... Https://cdn.fileinfo.com/img/ss/lg/jpg_44.JPG this is my picture.";
$d11="";$cs11 = array();$i=-1;
$sad111 = explode(" ",$sad222);
foreach ($sad111 as $sad)
{

if(strtolower(substr($sad,0,7))=="http://"||strtolower(substr($sad,0,7))=="ftps://"||strtolower(substr($sad,0,8))=="https://"||strtolower(substr($sad,0,6))=="ftp://"){
if(strtolower(substr($sad,strlen($sad)-4,4))==".jpg"||strtolower(substr($sad,strlen($sad)-4,4))==".jpe"||strtolower(substr($sad,strlen($sad)-4,4))==".jif"||strtolower(substr($sad,strlen($sad)-4,4))==".jfi"||strtolower(substr($sad,strlen($sad)-4,4))==".gif"||strtolower(substr($sad,strlen($sad)-4,4))==".png"||strtolower(substr($sad,strlen($sad)-4,4))==".bmp"||strtolower(substr($sad,strlen($sad)-4,4))==".dib"||strtolower(substr($sad,strlen($sad)-4,4))==".ico"||strtolower(substr($sad,strlen($sad)-5,5))==".jpeg"||strtolower(substr($sad,strlen($sad)-5,5))==".jfif"||strtolower(substr($sad,strlen($sad)-5,5))==".apng"||strtolower(substr($sad,strlen($sad)-5,5))==".tiff"||strtolower(substr($sad,strlen($sad)-4,4))==".tif"){
$d11="<img src='".$sad."' width='500' height='600'>";
$sad=$d11;}}$i++;
$cs11[$i]=$sad." ";
}

foreach ($cs11 as $dimz)
{  
echo $dimz;
}

?>