2015-06-14 80 views
2

時被替換不希望的路我用正則表達式我用鏈接替代的URL /井號標籤一個array使用preg_replace鏈接使用的preg_replace

$regs = array('!(\s|^)((https?://|www\.)+[a-z0-9_./?=;&#-]+)!i', '/#(\w+)/'); 
$subs = array(' <a href="$2" target="_blank">$2</a>', '<a href="/hashtag/$1" title="#$1">#$1</a>'); 

$output = preg_replace($regs, $subs, $content); 

如果$content有一個鏈接,爲前:https://www.google.com/,它會正確替換;如果有一個主題標籤,接着一文中,爲前:#hello更換過,但是,如果有一個主題標籤的鏈接,例如:https://www.google.com/#top更換如下:

#top" target="_blank">https://www.google.com/#top 
^^^^           ^^^^ 

,只有突出部分變成鏈接。

如何解決?

+1

什麼是你期望的輸出? – anubhava

+0

我的預期輸出如下:'https:// www.google.com /#top',但它只檢測#top(因此破壞html),並且沒有檢測到完全鏈接 – Igor

回答

1

這是因爲你的第二個正則表達式在數組中也是以字符串#之後匹配的部分。

改變你的正則表達式:

$regs = array('!(\s|^)((https?://|www\.)+[a-z0-9_./?=;&#-]+)!i', '/(?<=[\'"\s]|^)#(\w+)/'); 
$subs = array(' <a href="$2" target="_blank">$2</a>', '<a href="/hashtag/$1" title="#$1">#$1</a>'); 
$content = 'https://www.google.com/#top foobar #name'; 

# now use in preg_replace 
echo preg_replace($regs, $subs, $content); 

它會給你:

<a href="https://www.google.com/#top" target="_blank">https://www.google.com/#top</a> foobar <a href="/hashtag/name" title="#name">#name</a>

+0

它現在正在工作,但它不是更長的時間只檢測#標籤###test# – Igor

+1

完美!謝謝! – Igor