Subscribe to Grim's Projects        RSS Feed

preg_split as opposed to str_split

Icon Leave Comment
I submitted this as a snippet but it was turned down, and mostly I just wanted a place to put it so I'd have it available if I needed it in the future. Since I program for PHP 4 compatibility most often I found working on Mimesis that I needed to split a string at given intervals of length. The explode function only splits on given characters, and the str_split function only works in PHP 5. Looking at the php docs it was suggested somewhere that preg_split could be used in this capacity, but no user had posted on how. Took me a while but I came up with the following:
$splitString = preg_split('/(.{4})/s', 'Your string goes here.', -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
In this case I'm splitting the string 'Your string goes here.' into strings of four character length. To change the code to work for you, all you require is to replace your string and to change the integer 4 to the length you wish to split at.

0 Comments On This Entry