简体   繁体   English

PHP用锚标记替换文本中的多个URL

[英]PHP Replace multiple URL's in text with anchor tags

I have tried following so far: 到目前为止,我已经尝试过以下操作:

<?php

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$text = "The text I want to filter is here. It has urls http://www.example.com and http://www.example.org";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

       // make the urls hyper links
       $final = preg_replace($reg_exUrl, "<a href=\"{$url[0]}\">{$url[0]}</a> ", $text);

       echo $final;

} else {
       // if no urls in the text just return the text
       echo $text;
}

The only issue I am facing is that this is replacing both the URL's with the same url(that is the one found first). 我面临的唯一问题是,这将两个URL替换为相同的url(即第一个找到的URL)。 How do I loop this to replace each url with their own? 我该如何loop使用自己的网址替换每个网址?

Just use a single preg_replace() : 只需使用一个preg_replace()

$url_regex = '~(http|ftp)s?://[a-z0-9.-]+\.[a-z]{2,3}(/\S*)?~i';

$text = 'The text I want to filter is here. It has urls https://www.example.com and http://www.example.org';

$output = preg_replace($url_regex, '<a href="$0">$0</a>', $text);

echo $output;

In the replace part, you can refer to groups that were matched by using $0 , $1 etc... Group 0 is the whole match. 在替换部分,您可以引用使用$0$1等匹配的组...组0是整个匹配项。

Another example: 另一个例子:

$url_regex = '~(?:http|ftp)s?://(?:www\.)?([a-z0-9.-]+\.[a-z]{2,3}(?:/\S*)?)~i';

$text = 'Urls https://www.example.com and http://www.example.org or http://example.org';

$output = preg_replace($url_regex, '<a href="$0">$1</a>', $text);

echo $output;

// Urls <a href="https://www.example.com">example.com</a> and <a href="http://www.example.org">example.org</a> or <a href="http://example.org">example.org</a>

Using a preg_match() doesn't make sense, regex invocations are relatively expensive performance wise. 使用preg_match()没有意义,正则表达式调用在性能上是相对昂贵的。

PS: I also tweaked your regex a bit along the way. PS:我也对您的正则表达式进行了一些调整。

try this: 尝试这个:

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$text = "The text I want to filter is here. It has urls http://www.example.com and http://www.example.org";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

    // make the urls hyper links
    $final = preg_replace($reg_exUrl, '<a href="$0">$0</a>', $text);

    echo $final;

} else {
    // if no urls in the text just return the text
    echo $text;
}

output: 输出:

The text I want to filter is here. It has urls <a href="http://www.example.com">http://www.example.com</a> and <a href="http://www.example.org">http://www.example.org</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM