2013-08-04 82 views
1

下面是我的功能轉換從URL鏈接:如何跳過從功能處於轉換HREF鏈接到另一個鏈接

function url_to_link($string){ 

/*** make sure there is an http:// on all URLs ***/ 
$string = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2",$string); 

/*** make all URLs links ***/ 
$string = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</A>",$string); 

/*** make all emails hot links ***/ 
$string = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<A HREF=\"mailto:$1\">$1</A>",$string); 

return $string; 
} 

function update_todo() { 

    //var input 
    $projects_id = $_POST['projects_id']; 
    $content = url_to_link($_POST['content']); // <----- url_to_link() 
    $date_created = date('Y-m-d H:i:s'); 


    $sth = $this->db->prepare('SELECT * FROM `doc_to_do` where projects_id="'.$projects_id.'" '); 
    $sth->execute(); 
    $rows = $sth->fetchAll(); 
    $total_rows = count($rows); 

    if ($total_rows > 0) { 
     //update  
     $sql = "UPDATE `doc_to_do` SET content=? WHERE projects_id=?"; 
     $sth = $this->db->prepare($sql); 
     $sth->execute(array($content,$projects_id)); 
    } 
    else { 
     //insert 
     $sth = $this->db->prepare('INSERT INTO `doc_to_do` (projects_id, content, date_created) VALUES (:projects_id, :content, :date_created)'); 
     $sth->execute(array(':projects_id' => $projects_id, ':content' => $content, ':date_created' => $date_created)); 
    } 
} 

我嘗試我的內容有URL中使用上述功能成爲鏈接轉換。當第一次保存的鏈接是這樣的:

<p><a target="_blank" href="http://stackoverflow.com/">http://stackoverflow.com/</a></p> 

當我再次嘗試保存鏈接將打破:

<p><a target=\"_blank\" href=\"<a target="_blank" href="http://stackoverflow.com/">http://stackoverflow.com/</a>\"><a target="_blank" href="http://stackoverflow.com/">http://stackoverflow.com/</a></a></p> 

,你可以看到我的功能不夠好,它應該忽略鏈接,但轉換網址只有

+0

你爲什麼要這樣做兩次?在原始文本中是否有可能存在HTML,或者當通過函數兩次運行文本時,這只是一個問題? – deceze

+0

* [PHP正則表達式匹配HTML標籤外的關鍵字 mario

+0

@deceze看到我的完整代碼 – rusly

回答

0

我只是從我的內容第一條帶鏈接創建新的:

function url_to_link($string){ 

// remove all href to prevent duplicate(when convert) then create new one 
$string = strip_tags($string, '<p><b><i><s><ul><ol><li><strong>'); 

/*** make sure there is an http:// on all URLs ***/ 
$string = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2",$string); 

/*** make all URLs links ***/ 
$string = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</a>",$string); 

/*** make all emails hot links ***/ 
$string = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<a href=\"mailto:$1\">$1</a>",$string); 

return $string; 
} 
0

每次將它放入數據庫之前,請勿通過您的url_to_link函數運行文本。將用戶在數據庫中輸入的原始非HTML數據存儲起來,並僅在網站上顯示URL時將URL轉換爲HTML鏈接。因此,只有:

echo url_to_link($contentFromDatabase); 

它總是存儲在數據庫中未處理的,原始文本和儘可能晚地處理它是個好主意。首先,HTML鏈接僅針對HTML。想象一下你想在稍後的某個時間以純文本電子郵件或其他非HTML格式發送文本;如果你擁有的只是處理過的文本,那麼你遇到了麻煩。