An Upgraded explode() Function in PHP
In PHP, the explode() function splits a string into an array by a specified delimiter. Those who use this function regularly might have run into situations where the string contains the delimiter in parts you don’t actually want to split. For instance, splitting name|pass by | is completely fine, but if you have a string like myuser|pass|123, then pass and 123 will also be split apart. I encountered exactly this issue at work today, so I wrote a little helper function to handle it.
Let’s look at an example. Say we have a string:
$s = 'myinfo|myname|mypass|12|3|456|789';
Suppose 12|3 is the section we want to keep intact as a single block. We can solve this with our helper like this:
$rs = adv_explode($s, '|', 3, 2);
This means: split $s using | as the delimiter, keeping the first 3 segments and the last 2 segments as normal splits, and merging whatever is left in the middle. Haha, I didn’t include any strict parameter validation, so feel free to add that yourself if you need it. The code is actually very simple, written just to make life a bit easier for everyone!
1 | /** |