Reputation: 187
I have a string in PHP that I would like to split. This string is concatenation of ID numbers from the database.
An example of the string is below but it could be much long with each ID separated by "_":
ID_1_10_11_12
I would like to split the string into the following:
ID_1_10_11_12
ID_1_10_11
ID_1_10
ID_1
Then concatenate them in a new string reversed in order and then separated by spaces:
new string = "ID_1 ID_1_10 ID_1_10_11 ID_1_10_11_12"
I cant figure this out. I have tried exploding the original value into an array by "_" but that just leaves me with the numbers.
I would appreciate any advice on how I should approach this. For reference these ID's written to the class value of a checkbox so that parent and child values can be grouped and then manipulated by a jquery function.
Upvotes: 0
Views: 94
Reputation: 70149
Probably not the most elegant way, and it'll break if there are less than 2 IDs, but this will return the string you asked for:
$str = "ID_1_10_11_12";
//creates an array with all elements
$arr = explode("_", $str);
$new_str = ' ID_' . $arr[1];
for ($i=2; $i<count($arr); $i++)
{
$tmp = explode(" ", $new_str);
$new_str .= " " . $tmp[$i-1] . "_" . $arr[$i];
}
$new_str = trim($new_str);
echo $new_str; //echoes ID_1 ID_1_10 ID_1_10_11 ID_1_10_11_12
I don't see much usability for it but there you go.
You can then simply explode(" ", $new_str)
and you'll also have an array with all the elements in that string, which you can transverse the way you want.
Obviously, you can also add a if (count($arr) < 3)
before the for
to check if there are less than 2 array elements after the ID
and exit the function printing the $new_str
without the white space with trim($new_str)
if inputting less than 2 ID arrays is a concern.
edit: Trimmed the left white space.
Upvotes: 1
Reputation: 11440
My testing local server is down to verify this, but I believe this will work.
<?php
/*
ID_1_10_11_12
ID_1_10_11
ID_1_10
ID_1
ID_1 ID_1_10 ID_1_10_11 ID_1_10_11_12
*/
$str = "ID_1_10_11_12";
$delim = "_";
$spacer = " ";
$ident = "ID";
$out = "";
// make an array of the IDs
$idList = explode($delim, $str);
// loop through the array
for($cur = 0; $cur >= count($idList); $cur++){
// reset the holder
$hold = $ident;
// loop the number of times as the position beyond 0 we're at
for($pos = -1; $pos > $cur; $pos++){
// add the current id to the holder
$hold .= $delim . $idList[$cur]; // "ID_1"
}
// add a spacer and the holder to the output if we aren't at the beginning,
// otherwise just add the holder
$out .= ($cur != 0 ? $spacer . $hold : $hold); // "ID_1 ID_1_10"
}
// output the result
echo $out;
?>
Upvotes: 0