2012-03-07 30 views
0

我有一些代碼,雖然它有效,但它使我的內容不穩定。讓我解釋。REGex導致內容看起來很有趣(排除代碼故障)

我創建的文本聊天應用程序來研究PHP等,並且長話短說,用戶鍵入的消息,該消息被以dB爲單位記錄並打印回出到在某些領域(下同)

頁這是頁面如何得到它的內容(簡稱所以我不補的代碼頁)

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 --其中 出現在一個灰色的ISH格。

現在,我遇到的問題是,獲取鏈接以顯示鏈接,當回顯到頁面時。

這是我去的代碼(用別人的幫助)

//====== 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技能停在那裏哈哈。 任何提示/幫助/解釋等不愉快地接受。

回答

2

看起來好像是echo ing當時它preg_replaces,而不是將其保存爲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); 
+0

釘正確的頭部!謝謝。 – somdow 2012-03-07 04:50:31