2011-08-28 105 views
1

我有一個函數(我沒有寫)在一個已經使用了好幾年的頁面頭部現有的php標籤中,解析URL和電子郵件地址使它們可點擊鏈接:php mysql在函數內部檢查

function ParseURLs($str){ 
    if(isset($str)){ 
    $Output=strip_tags($str); 
    $Output=preg_replace("/(\swww\.)|(^www\.)/i"," http://www.",$Output); 
    $Output=preg_replace("/\b(((ftp|http(s?)):\/\/))+([\w.\/&=?\-~%;]+)\b/i" 
      ,"<a href='$1$5' target='_blank' rel='nofollow'>$1$5</a>",$Output); 
    $Output=preg_replace("/\b([\w.]+)(@)([\w.]+)\b/i" 
      , "<a href='mailto:[email protected]$3'>[email protected]$3</a>",$Output); 
    return nl2br($Output); 
    } 
} 

我想更換的rel =「nofollow的」與一個MySQL數據庫經現場的PHP檢查,並讓它只放了rel='nofollow'如果與dBASE字段爲空。我試圖做到這一點在函數像這樣的東西這是我的出發點更換rel='nofollow'

<?php if (empty($row_rswhatever['linkfollow'])) {echo "rel='nofollow'";}?> 

或者只是這樣的:

if (empty($row_rswhatever['linkfollow'])) {echo "rel='nofollow'";} 

我已經試過了一百種不同的方式(東西好的通常遲早會發生),但無法使其發揮作用。根據以往的經驗,我知道我可能會在多個問題上錯失良機,並希望得到任何幫助或指導。謝謝。

回答

0

一個簡單的/懶惰的方式做到這一點是繼續做你現在正在做,但最後$output=preg_replace後添加if測試,如果你不想做rel='nofollow',只是用str_replace將其刪除。

即。

function ParseURLs($str) 
{ 
    if(isset($str)){ 
     $Output=strip_tags($str); 
     $Output=preg_replace("/(\swww\.)|(^www\.)/i"," http://www.",$Output); 
     $Output=preg_replace("/\b(((ftp|http(s?)):\/\/))+([\w.\/&=?\-~%;]+)\b/i","<a href='$1$5' target='_blank' rel='nofollow'>$1$5</a>",$Output); 
     $Output=preg_replace("/\b([\w.]+)(@)([\w.]+)\b/i", "<a href='mailto:[email protected]$3'>[email protected]$3</a>",$Output); 

     if (empty($row_rswhatever['linkfollow'])) { 
      $Output = str_replace(" rel='nofollow'", "", $Output); 
     } 

     return nl2br($Output); 
    } 
} 
0

不知道到底是什麼你會在數據庫中檢查:

function ParseUrls($str) { 
    $sql = "SELECT ... FROM yourtable WHERE somefield='" . mysql_real_escape_string($str) ."'"; 
    $result = mysql_query($sql) or die(mysql_error()); 
    $rel = (mysql_num_rows($result) == 0) ? ' rel="nowfollow"' : ''; 
    blah blah blah 
} 

順便說一句,isset檢查是在你的代碼沒用。函數參數沒有默認值(function x($y = default)),所以如果在調用代碼中沒有指定參數,它將在PHP中導致致命錯誤。

這也假設你已經連接到你的代碼中的其他地方的MySQL,並且正在使用mysql庫(不是mysqli或者pdo或者db或者其他)。

+0

感謝您的快速回復。我只是將一個默認值爲空的dbase字段添加到現有的mysql表中,並且如果我們想要在創建該行時創建的鏈接上放置nofollow,就會在該字段中放置一個字符。 nofollow每個鏈接都沒有一個好的seo或其他理由,而且很多都是高質量的網站。是的,代碼中的這個函數之上已經有了一個連接。 – kidcobra