Reputation: 303
I have this:
$following_user_id .= $row['following_user_id'];
and I get:
44443344330
then I separate with commas:
44,44,33,44,33,0,
but I don't want the last comma on the last number.
Is this possible?
Upvotes: -4
Views: 4746
Reputation: 48050
You can use preg_replace()
to insert a comma after every two characters. (Demo)
$input = '44443344330';
echo preg_replace('/..\K/', ',', $input);
// 44,44,33,44,33,0
If in other circumstances, your input string has an even number of characters and you still don't want the trailing comma, then use /..\K(?!$)/
which uses a negated lookahead for the end of the string.
Or without regex, you can use word_wrap()
. The true
4th parameter is necessary to force the function to "break long words". (Demo)
$input = '44443344330';
echo wordwrap($input, 2, ',', true);
// 44,44,33,44,33,0
This approach will not add the trailing comma even if the string has an even number of characters.
chunk_split()
is not suitable for this task because it will append the unwanted comma at the end of the string.
echo chunk_split($input, 2, ',');
outputs: 44,44,33,44,33,0,
Upvotes: 0
Reputation: 1256
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Upvotes: 0
Reputation: 3290
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Upvotes: 1
Reputation:
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Upvotes: 1
Reputation: 28936
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Upvotes: 1
Reputation: 15230
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
Upvotes: 1
Reputation: 1
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);
Upvotes: -1
Reputation: 819
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
Upvotes: 0