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.
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:
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 theforto check if there are less than 2 array elements after theIDand exit the function printing the$new_strwithout the white space withtrim($new_str)if inputting less than 2 ID arrays is a concern.edit: Trimmed the left white space.