我有这个:
$following_user_id .= $row['following_user_id'];
我得到:
44443344330
然后我用逗号分隔:
44,44,33,44,33,0,
但我不想在最后一个数字上使用最后一个逗号。
这可能吗?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
您可以将字符串拆分为字符数组,然后将数组内爆。
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
将数据收集到字符串数组中并使用 implode 函数:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
检查内爆:http://php.net/manual/en/function.implode.php
代码示例:我假设您使用某种循环?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode 不应在该字符串的末尾插入逗号。您确定数组序列末尾没有空字符串吗?
无论哪种方式,要修复您拥有的字符串,只需删除字符串的最后一个字符即可:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
此外,如果您不打算使用非逗号分隔的数字集,为什么不在每次添加用户 ID 时添加一个逗号。这样你甚至不必使用内爆功能。
这对我有用:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
您可以使用
preg_replace()
在每两个字符后插入一个逗号。 (演示)
$input = '44443344330';
echo preg_replace('/..\K/', ',', $input);
// 44,44,33,44,33,0
如果在其他情况下,您的输入字符串具有偶数个字符,并且您仍然不需要尾随逗号,则使用
/..\K(?!$)/
,它对字符串末尾使用否定的前瞻。
或者没有正则表达式,您可以使用
word_wrap()
。 true
第四个参数是强制函数“打破长单词”所必需的。 (演示)
$input = '44443344330';
echo wordwrap($input, 2, ',', true);
// 44,44,33,44,33,0
即使字符串有偶数个字符,此方法也不会添加尾随逗号。
chunk_split()
不适合此任务,因为它会在字符串末尾附加不需要的逗号。echo chunk_split($input, 2, ',');
输出:44,44,33,44,33,0,
尝试使用数组,例如
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);