我试图模仿Twitter的哈希标记系统,用可点击的链接替换所有主题标签。我把一个有用的片段放在一起,但我发现如果两个单词有类似的开头,那么较长的单词只会被替换(通过可点击的链接)到较短单词停止的长度。也就是说,如果我在#toolbox'中有一个句子#to; #tool成为一个链接,只有#toolbox中的#tool成为一个链接,而不是整个#toolbox。
以下是摘录:
<?php
//define text to use in preg_match and preg_replace
$text = '#tool in a #toolbox';
//get all words with hashtags
preg_match_all("/#\w+/",$text,$words_with_tags);
//if there are words with hash tags
if(!empty($words_with_tags[0])){
$words = $words_with_tags[0];
//define replacements for each tagged word,
// $replacement is an array of replacements for each word
// $words is an array of words to be replaced
for($i = 0; $i < sizeof($words) ; $i++ ){
$replacements[$i] = '<a href="'.trim($words[$i],'#').'">'.$words[$i].'</a>';
// format word as /word/ to be used in preg_replace
$words[$i] = '/'.$words[$i].'/';
}
//return tagged text with old words replaced by clickable links
$tagged_text = preg_replace($words,$replacements,$text);
}else{
//there are no words with tags, assign original text value to $tagged_text
$tagged_text = $text;
}
echo $tagged_text;
?>
答案 0 :(得分:1)
capturing如何做一个简单的preg_replace()
$tagged_text = preg_replace('~#(\w+)~', '<a href="\1">\0</a>', $text);
Test at eval.in 输出到:
<a href="tool">#tool</a> in a <a href="toolbox">#toolbox</a>
答案 1 :(得分:0)
<?php
$string = "#tool in a #toolbox";
$str = preg_replace_callback(
'/\#[a-z0-9]+/',
function ($matches) {
return "<a href=\"". ltrim($matches[0], "#") ."\">". $matches[0] ."</a>";
}, $string);
echo $str;
//Output: <a href="tool">#tool</a> in a <a href="toolbox">#toolbox</a>