2014-01-20 48 views
0

我運行這段代碼:PHP刪除 '' 如果不存在

$stmt = $pdo_conn->prepare("SELECT * from admin where support_emails = :support_emails and logged = :logged and disabled = :disabled "); 
     $stmt->execute(array(':support_emails' => 'Y', ':logged' => 'in', ':disabled' => '')); 
     $records = $stmt->fetchAll(PDO::FETCH_ASSOC); 
     if(count($records) > 0) { 
      foreach($records as $records2) { 
       if(filter_var($records2["email"], FILTER_VALIDATE_EMAIL)) { 
        $SupportEmailList = $records2["email"].', '.$SupportEmailList; 
       } 
       if(!empty($SupportEmailList)) { 
        $SupportEmailList = substr($SupportEmailList, 0, -2); // removes last 2 characters (`, `) from end of string 
       } 
      } 
     } 

,當我在SQL

我添加了一些運行,返回

[email protected], [email protected] 

if(!empty($SupportEmailList)) { 
        $SupportEmailList = substr($SupportEmailList, 0, -2); // removes last 2 characters (`, `) from end of string 
       } 

刪除', '從字符串如果最後的結果是不存在的結束,但它似乎是創建以下:

[email protected], [email protected] 

而不是:

[email protected], [email protected] 
+0

而問題是什麼? –

+0

你想添加每個emailadres的字符串分隔,? –

+0

耶基本上創建一個字符串與從逗號分隔的數據庫返回的所有電子郵件地址 – user2710234

回答

6

我建議讓您的結果在一個數組,並使用implode(或加入)用逗號加入他們。

這樣你就不必處理尾隨逗號問題。

$email_address = array(); 

foreach($records as $records2) { 
    if(filter_var($records2["email"], FILTER_VALIDATE_EMAIL)) { 
     array_push($email_address, $records2["email"]); 
    } 
} 

$comma_separated_email_address = implode(",", $email_address); 

echo $comma_separated_email_address ; 
+0

舉個例子...? –

+0

編輯我的答案 – raj

0

嘗試trim()。您可以通過字符作爲第二個參數的列表中選擇你想從字符串的開始/結束脩剪什麼:

$example_1 = '[email protected], [email protected]'; 
$example_2 = '[email protected], [email protected], '; 

$example_1 = trim($example_1, ', '); 
$example_2 = trim($example_2, ', '); 

var_dump($example_1); // string(38) "[email protected], [email protected]" 
var_dump($example_2); // string(38) "[email protected], [email protected]" 

var_dump(explode(', ', $example_1)); 
// array(2) { [0]=> string(18) "[email protected]" [1]=> string(18) "[email protected]" } 
+0

trim()從字符串的開頭和結尾修剪字符(',')。你想做什麼?如果你想按''分割,嘗試'explode()'。 – Sam

+0

修剪僅適用於字符串的開頭和結尾。 – SenseException

+0

@SenseException我只是回答OP的問題:*從字符串*的末尾刪除',',儘管它看起來好像取決於某種解釋。 – Sam

0

您可以用explodeimplode分割你的字符串再次

$data = explode(',', $elements); 
$cleanedData = implode(',', $data); 

你可以修剪你的數據在修整$ data數組的所有值空間

for ($i = 0; $i < count($data); $i++) 
    $data[$i] = trim($data[$i]);