我在buildinternet.com上發現了此功能。在php中添加超文本鏈接
function tag_it($text) {
$text = preg_replace("/:(\w+):/", '<a href="http://www.example.com/page/$1/" title="$1" target="_blank">$1</a>',$text);
return $text;
}
它的作用是添加超鏈接到包含在詞「:」而問題是,它與單個詞只適用,它不`噸與具有單引號的話工作。
所以,如果我這樣做,
$test = "one :word1:, :two words:, :this is a phrase:, this has a single quote :don't: or :don't forget:.";
echo tag_it($test);
僅對:字詞1:將添加一個超鏈接,其餘的將被忽略。
我不知道太多的PHP,我會很感激,如果有人可以使這個功能與多個單詞和單引號也工作。
謝謝!
編輯:
所以我曾嘗試以下,以一個不同的鏈接添加到
function tag_it($text) {
$out = preg_replace_callback(
"/:([^\:]+):/",
function($m) {
$linkText = $m[1];
$link = str_replace('"', '', $m[1]);
$link = str_replace("'", "", $m[1]);
$link = str_replace(" ", "_", $link);
return '<a href="http://www.example.com/page/'.$link.'/" title="'.$linkText.'" target="_blank">'.$linkText.'</a>';
},
preg_replace_callback(
"/#([^\#]+)#/",
function($m1) {
$linkText1 = $m1[1];
$link1 = str_replace('"', '', $m1[1]);
$link1 = str_replace("'", "", $m1[1]);
$link1 = str_replace(" ", "_", $link1);
return '<a href="http://www.example.com/blog/'.$link1.'/" title="'.$linkText1.'" target="_blank">'.$linkText1.'</a>';
},
$text
)
);
return $out;
}
$test = "one :word:, #two words#, :this is a phrase:, this has a single quote :don:'t or :don't forget:.";
echo tag_it($test);
括在 「#」 字和我得到這個
one word, two_words,_/" title="//www.example.com/blog/two_words/" title="two words" target="_blank">two words, " target="_blank">//www.example.com/blog/two_words/" title="two words" target="_blank">two words, this is a phrase, this has a single quote don't or don't forget:.
似乎爲包含在「:」中的第一個單詞工作,並試圖使用「#」中包含的單詞進行工作,但一路上正在發生一些事情,我無法通過把它弄出來。
任何提示真的很感激。
謝謝!
我正要詢問如何從href屬性替換空間,我不認爲有人會注意到。你的解決方案工作的很好,我只需要添加這一行'$ link = str_replace('','_',$ link);'替換空格。非常感謝。 –