php preg_match_all/preg_replace正在截断类似匹配的替换

php preg_match_all/preg_replace正在截断类似匹配的替换,php,regex,preg-replace,preg-match,Php,Regex,Preg Replace,Preg Match,我试图模仿Twitter的散列标签系统,用可点击链接替换所有的散列标签。我整理了一个有用的片段,但我发现如果两个单词的开头相似,那么长的单词只会被替换为短单词停止的长度(通过可点击的链接)。也就是说,如果我有一个句子“#工具箱中的工具”,那么#工具箱中的工具成为链接,只有#工具箱中的工具成为链接,而不是整个#工具箱 以下是片段: <?php //define text to use in preg_match and preg_replace $text = '#tool in a

我试图模仿Twitter的散列标签系统,用可点击链接替换所有的散列标签。我整理了一个有用的片段,但我发现如果两个单词的开头相似,那么长的单词只会被替换为短单词停止的长度(通过可点击的链接)。也就是说,如果我有一个句子“#工具箱中的工具”,那么#工具箱中的工具成为链接,只有#工具箱中的工具成为链接,而不是整个#工具箱

以下是片段:

<?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;


?>

您可以使用

做一个简单的

$taged_text=preg_replace(“~#(\w+)”,“$text”);
输出至:


好极了。神奇的非常感谢。然而,我仍然不明白为什么我的漫长过程没有起作用。我希望有人能指出我在代码中出错的地方。从理论上讲,我输入的内容应该是有效的(我相信是的),但它根本不起作用。@Dara You're welcome:)它失败是因为
$words[$I]='/'。$words[$I]./'
您忘记在单词后面添加a:
'/.$words[$i].\b/'
<?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>
$tagged_text = preg_replace('~#(\w+)~', '<a href="\1">\0</a>', $text);
<a href="tool">#tool</a> in a <a href="toolbox">#toolbox</a>