這會稍微提高原始圖案的準確性。我的模式將以比您的模式快兩倍的速度運行。我刪除了不需要的/未使用的捕獲組,提高了可選的模式精度//
,在模式末尾添加了一個不區分大小寫的標誌,刪除了不必要的轉義,爲簡潔起見,基本上簡化了您的模式。
Pattern Demo With Replacement
代碼:(Demo)
function linkify($text){
$capture='@(?:http(s)?://)?([a-z][-\w]+(?:\.\w+)+(?:\S+)?)@i';
$replace='<a href="http$1://$2" target="_blank" title="$0">$0</a>';
$string = preg_replace($capture,$replace,$text);
return $string;
}
echo linkify("Here is a sentence with a url containing a query string: https://www.google.com/search?q=mickmackusa&oq=mickmackusa&aqs=chrome..69i57j69i60.271j0j7&sourceid=chrome&ie=UTF-8 all good."),"\n\n---\n\n";
echo linkify("http://google.com"),"\n\n---\n\n";
echo linkify("http://google.com.au"),"\n\n---\n\n";
echo linkify("https://google.com.au"),"\n\n---\n\n";
echo linkify("www.google.com"),"\n\n---\n\n";
echo linkify("google.com"),"\n\n---\n\n";
echo linkify("I went to the local food store and bought some food.\n\nI was able to find everything"),"\n\n---\n\n";
echo linkify("I went to the local food store and bought some food.
I was able to find everything");
輸出:
Here is a sentence with a url containing a query string: <a href="https://www.google.com/search?q=mickmackusa&oq=mickmackusa&aqs=chrome..69i57j69i60.271j0j7&sourceid=chrome&ie=UTF-8" target="_blank" title="https://www.google.com/search?q=mickmackusa&oq=mickmackusa&aqs=chrome..69i57j69i60.271j0j7&sourceid=chrome&ie=UTF-8">https://www.google.com/search?q=mickmackusa&oq=mickmackusa&aqs=chrome..69i57j69i60.271j0j7&sourceid=chrome&ie=UTF-8</a> all good.
---
<a href="http://google.com" target="_blank" title="http://google.com">http://google.com</a>
---
<a href="http://google.com.au" target="_blank" title="http://google.com.au">http://google.com.au</a>
---
<a href="https://google.com.au" target="_blank" title="https://google.com.au">https://google.com.au</a>
---
<a href="http://www.google.com" target="_blank" title="www.google.com">www.google.com</a>
---
<a href="http://google.com" target="_blank" title="google.com">google.com</a>
---
I went to the local food store and bought some food.
I was able to find everything
---
I went to the local food store and bought some food.
I was able to find everything
這可能不是所有可能的URL的靈丹妙藥,但它是一個合理的基礎。如果您發現某些字符串未按預期更換,則該模式可能需要進行一些調整。
模式更新/擴展到包括網址子域:
~(?:ht{2}p(s)?:/{2})?([a-z][-\w.]+(?:\.\w+)+(?:\S+)?)~i
// new dot here---------------^
我僅僅增加了一個點到字符類。
似乎是關於你的環境,在這裏工作得很好:https://3v4l.org/j2TO0 那些
標籤來自哪裏? – mulquin
謝謝你,你是對的我沒有注意到nl2br()正在運行在文本上之前打這個功能。 –
預期產量是多少?我在你的模式中看到一些不必要的東西。 – mickmackusa