如果不存在,PHP将从字符串中删除','

时间:2014-01-20 20:53:47

标签: 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
                }
            }
        }

返回

email1@domain1.com, email2@domain2.com

当我在SQL中运行时

我添加了:

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

如果最后一个结果不存在,则从字符串末尾删除', ',但它似乎是在创建以下内容:

email1@domain1.com, email2@domain2.c

而不是:

email1@domain1.com, email2@domain2.com

5 个答案:

答案 0 :(得分:6)

我建议您将结果保存在一个数组中,然后使用implode(或者join)将它们与逗号结合起来。

这样您就不必处理尾随逗号问题了。

$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 ;

答案 1 :(得分:0)

试试trim()。您可以将字符列表作为第二个参数传递,以从字符串的开头/结尾选择要修剪的内容:

$example_1 = 'email1@domain1.com, email2@domain2.com';
$example_2 = 'email1@domain1.com, email2@domain2.com, ';

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

var_dump($example_1); // string(38) "email1@domain1.com, email2@domain2.com"
var_dump($example_2); // string(38) "email1@domain1.com, email2@domain2.com"

var_dump(explode(', ', $example_1));
// array(2) { [0]=> string(18) "email1@domain1.com" [1]=> string(18) "email2@domain2.com" }

答案 2 :(得分:0)

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

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

您可以修剪数据中的空间,修剪$ data array中的所有值

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

答案 3 :(得分:0)

我不明白你的问题,删除','如果它不存在?无论如何,您应该使用PDO::FETCH_NUM获取数据。通过这种方式,您将获得一系列电子邮件,例如['email1@domail.com', 'email2@mail.com'],然后如果您想使用'email1@domail.com, email2@mail.com',请使用implode将元素与字符串连接起来。

答案 4 :(得分:0)

做到:

$emails  = " email1@domain1.com , fsdfsdffdsffds , email2@domain2.com,sddsfsdsd ";
$emails = array_map('trim',explode(',',$emails));

$out = array_map(function($email){
                return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? $email : null;
             },$emails);

$emails = implode(',',array_filter($out));
print_r($emails);
// email1@domain1.com,email2@domain2.com