0

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

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 开头的链接。

你会怎么做?

非常感谢 :)

丹尼斯

4

2 回答 2

2

这两个链接结合起来怎么样:

确定 URL 是否是 PHP 中的图像的最佳方法

PHP 正则表达式文本 URL 到 HTML 链接

$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 ) );
}
于 2012-05-06T16:20:19.543 回答
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;
}

?>
于 2019-07-09T08:29:25.353 回答