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

Rip*_*ter 1 php regex

到目前为止我已经尝试过以下操作:

<?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;
}
Run Code Online (Sandbox Code Playgroud)

我面临的唯一问题是,这会将两个 URL 替换为相同的 URL(即第一个找到的 URL)。我如何用loop自己的网址替换每个网址?

Ham*_*mZa 5

只需使用一个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;
Run Code Online (Sandbox Code Playgroud)

在替换部分,您可以使用 等引用匹配的组$0...$1组 0 是整个匹配。

另一个例子:

$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>
Run Code Online (Sandbox Code Playgroud)

使用 apreg_match()没有意义,正则表达式调用在性能方面相对昂贵。

PS:我还对你的正则表达式进行了一些调整。