在每个第二个字符后插入一个逗号,而不在字符串末尾添加逗号

问题描述 投票:0回答:8

我有这个:

$following_user_id .= $row['following_user_id'];

我得到:

44443344330

然后我用逗号分隔:

44,44,33,44,33,0, 

但我不想在最后一个数字上使用最后一个逗号。

这可能吗?

php string insertion delimited
8个回答
1
投票
$following_user_ids = array();

//loop this:
$following_user_ids[] = $row['following_user_id'];

$user_ids_string = implode(',',$following_user_ids);

1
投票

您可以将字符串拆分为字符数组,然后将数组内爆。

$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);

echo implode( ',', $array );

1
投票

将数据收集到字符串数组中并使用 implode 函数:

$uids = array();
while($row = mysql_fetch_assoc($result)){
    array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);

1
投票

检查内爆: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); 

0
投票

Implode 不应在该字符串的末尾插入逗号。您确定数组序列末尾没有空字符串吗?

无论哪种方式,要修复您拥有的字符串,只需删除字符串的最后一个字符即可:

$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);

此外,如果您不打算使用非逗号分隔的数字集,为什么不在每次添加用户 ID 时添加一个逗号。这样你甚至不必使用内爆功能。


0
投票

这对我有用:

<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>

0
投票

您可以使用

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,


-1
投票

尝试使用数组,例如

<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);
© www.soinside.com 2019 - 2024. All rights reserved.