我在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);'替换空格。非常感谢。 –