REGex导致内容看起来很有趣(故障排除代码)


REGex causing content to look funny(troubleshoot code)

我有一些代码,虽然它可以工作,但它使我的内容不稳定。让我解释一下。

我创建了一个用于学习PHP等的文本聊天应用程序,长话短说,用户键入一条消息,消息会登录到数据库中,并将其打印回特定字段的页面上(下面)

这就是页面获取内容的方式(简而言之,这样我就不会用代码填充页面)

while($row = mysqli_fetch_array($dbqDoIt4_mssgs)){
            $i++;
             //====== TURN REGULAR LINKS TO CLICKY LINKS USING REGEXP.
$URL = "/(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)?/";
$text = $row['mssg'];
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
       // make the urls hyper links
       echo preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a> ", $text);
}
//======= 

            echo '<div class="holdChat">
                        <span class="orangeBigger">' . strtoupper($row['user']). '</span>' . ' ' . '<span class="txtSaid">said:</span> ' . '<span style="color:#171717;">' . $text . '</span>' . '</div>' . 
            '<div class="chatTimeBox">' . $row['time'] . '</div><br/>';
                if($i == 20){
                    break;  
                }
            }

从本质上讲,这会使所有内容达到20,并中断等…

因此,将上面的内容放在一行中,得到USER-NAME SAID: " --message here --出现在灰色的潜水器中。

现在,我遇到的问题是,当对页面进行echo时,让链接显示为链接。

这是我使用的代码(在其他人的帮助下)

//====== TURN REGULAR LINKS TO CLICKY LINKS USING REGEXP.
$URL = "/(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)?/";
$text = $row['mssg'];
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
       // make the urls hyper links
       echo preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a> ", $text);
}
//======= 

我目前遇到的问题是,当帖子中写下链接时,它会重复写下的内容。。。或者更确切地说,它在页面上出现了两次。如果帖子没有任何链接,它会显示为应该显示的内容。

因此,例如,如果文本中没有链接,它看起来像USER-NAME SAID: " --message here --

如果文本上有任何链接,我会得到一个像一样的双帖子

USER-NAME SAID: " --message here --
USER-NAME SAID: " --message here --

这一切都结束了。

我无计可施。。。我的php技能到此为止,哈哈。任何提示/帮助/解释等我都乐意接受。

看起来它在preg_replaces时是echo,而不是将其保存为稍后的echo。尝试更改:

echo preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a> ", $text);

收件人:

$text = preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a> ", $text);