在不使用循环的情况下,将逗号分隔的值字符串转换为另一种格式


PHP Convert a string of comma separated values into another format without using a loop

在php中,如果我有一个逗号分隔的数据字符串,像这样来自数据库:

John,Paul,Ringo,George

我怎么能把它转换成这样的东西,不使用for循环或任何额外的处理。php有这样的函数吗?

$str = 'John','Paul','Ringo','George';

我目前使用爆炸拆分字符串,然后重新格式化它。不管怎样,不这样做就能达到这个目的?

格式化字符串被发送到SQL,在MySQL IN()函数中使用。

如果你绝对不想使用explosion(),你可以使用

$str = 'John,Paul,Ringo,George';
$newStr = "'" . str_replace(",","','", $str) . "'";

你可以使用preg_replace = $1 thing

更新:参见用法示例:

echo preg_replace('((''w+)(,?))', '"$1"$2', 'John,Paul,Ringo,George');

可以像下面这样使用

$db_data = 'John,Paul,Ringo,George';//from your db
$l = explode(',',$db_data);
echo "select * from table where column IN('".implode("','",$l)."')";
输出

:

select * from table where column IN('John','Paul','Ringo','George')

可以在PHP中使用explodeimplode函数

$names = explode(',', 'John,Paul,Ringo,George');
echo implode(',', $names);

我希望我没看错你:

$str_1 = 'John,Paul,Ringo,George';
$str_2 = explode(',', $str_1);
$str_3 = implode(''',''', $str_2);
$str_4 = ''''.$str_3.'''';
echo $str_4;

输出:'John','Paul','Ringo','George'

$l = 'John,Paul,Ringo,George';
$lx = "'" . implode("','", explode(",", $l)) . "'";
echo $lx; // 'John','Paul','Ringo','George'