编辑php url链接函数


Edit php urls to link function

我有一个php函数,可以将url更改为链接。但当我插入<img src="http://somelink.com/picture.jpg">格式的图片时,我遇到了问题,它也会将内部url更改为链接。我应该如何防止这种情况发生?

<?php
$string='http://www.somelink.com';
echo makelink($string);
function makeLink($string){
$string = preg_replace("/([^'w'/])(www'.[a-z0-9'-]+'.[a-z0-9'-]+)/i","$1http:$2",$string);
$string = preg_replace("/(['w]+:'/'/['w-?&;#~='.'/'@]+['w'/])/i","<a target='"_blank'" href='"$1'">$1</A>",$string);
$string = preg_replace("/(['w-?&;#~='.'/]+'@('[?)[a-zA-Z0-9'-'.]+'.([a-zA-Z]{2,3}|[0-9]{1,3})(']?))/i","<A HREF='"mailto:$1'">$1</A>",$string);
return $string;
}
?>

例如,当我有这样的输入时:

<img src="http://somelink.com/img.jpg"> http://somelink.com

我需要这样的输出:

<img src="http://somelink.com/img.jpg"> <a href="http://somelink.com" target="_blank">http://somelink.com</a>

我的代码现在所做的是:

<img src="<a href="http://somelink.com/img.jpg" target="_blank">http://somelink.com/img.jpg</a>"> <a href="http://somelink.com" target="_blank">http://somelink.com</a>

我希望你能看到问题

您可以在REGEX中使用负查找来检查是否有东西不在您想要匹配的东西之前

假设您有以下匹配URL的表达式:

((?:http(?:s)?://)(?:www'.)?[-A-Z0-9.]+(?:'.com)[-A-Z0-9_./]?(?:[-A-Z0-9#?/]+)?)

此表达式将匹配以下类型的URL:

http://www.example.com
http://example.com/
https://www.example.com/seconday/somepage#hashes?parameters
https://www.example.com/seconday/
http://www.example.com/seconday
http://example.com/seconday
http://example.com/seconday/

因此,你可以在它的前面添加一个否定的lookbacking来检查引号、勾号或等号。如果它找到了其中一个,那么它就不会匹配。

以下是负面回顾的样子:

(?<!(?:"|'|=))

你可以把它放在另一个REGEX前面。这意味着:

(?<!   (?:   "|'|=   )   )
 1      2      3     4   5
  1. (?<! Negative Lookbacking-这表示确保接下来出现的内容不能出现在字符串前面
  2. (?:非捕获圆括号-我们将放置一个由引号"、勾号'或等号=组成的组,但我们不想捕获它。我们只想检查其中的任何一个。默认情况下,REGEX会记住括号(内的任何内容,因此我们添加?:来告诉它不要这样做
  3. "|'|=查找引号"、刻度'或等号=
  4. ) "|'|=的"或"分组的右括号
  5. )负查找的右括号

好吧,综合起来,REGEX看起来是这样的:

(?<!(?:"|'|=))((?:http(?:s)?://)(?:www'.)?[-A-Z0-9.]+(?:'.com)[-A-Z0-9_./]?(?:[-A-Z0-9#?/]+)?)

这是REGEX 演示的链接

这里有一个链接到一个PHP脚本中的REGEX演示

实际上,我对REGEX所做的唯一一件事就是转义tick,因为我使用tick来封装我的表达式。

你可能想试试这个:

<?php
    $html = '<img src="http://somelink.com/img.jpg"> http://somelink.com';
    $link = preg_replace('%<img src="(.*)/(.*?)">'s*(.*?)'s*$%m', '<img src="$1/$2"> <a href="$1" target="_blank">$3</a>', $html );
    echo $link;
`   //<img src="http://somelink.com/img.jpg"> <a href="http://somelink.com" target="_blank">http://somelink.com</a>
?>

演示
https://ideone.com/fgGaYK