This Tutorial will focus on methods to convert a string to an array. For the conversion to be possible, the string will either have to contain a matchable pattern that it can be split by – often this will just be a comma – but sometimes you would need to use regular expressions to match more complex patterns; or each part needs to be a fixed width, so that the split can be split with the str_split function.
If the string contains a list of keywords, its a good idea to separate each keyword by a single comma or space, as this will make it much easier to split the string using explode, or similar functions. To convert a string to an array using a regular expression, you can use the preg_split function.
This tutorial might not be very detailed, but it does show how you can use the different methods that we mentioned. You may want to take a look on other tutorials dedicated to a specific function to learn more, these, when available, will be listed in the See also section of this tutorial.
Using the Str_split Function
The Str_split function will split a string into an array, by either letting each character become an element in the array, or by a fixed width provided in the second parameter.
<?php $str = "Just a test"; $arr1 = str_split($str); // Splits by 1 character. $arr2 = str_split($str, 3); // splits the string by 3 characters. print_r($arr1); print_r($arr2); ?>
Array (  => J  => u  => s  => t  =>  => a  =>  => t  => e  => s  => t ) Array (  => Jus  => t  => a t  => est )
You can change the second parameter to match the number of characters that you want to be contained in each chunk. Using str_split will simply break down the string into smaller chunks, generally not very useful. So lets instead go through some of the other methods mentioned earlier.
Using Explode to split a string
This function is more useful, as it will allow you to split a string by another string. Typically you would use this function to convert a string of keywords into an array of keywords; which would allow your to more easily work with each keyword.
<?php $keywords = 'Blogging SEO Linkbuilding'; $pieces = explode(' ', $keywords); echo $pieces; // Blogging echo $pieces; // SEO ?>
This will also allow you to easily iterate over your array with normal loops, or foreach.
Using preg_split to convert strings to arrays
Finally, preg_split, the king of all the splitting functions. It stands completely overpowered when compared with Explode and Str_split, since it allows you to use regular expressions to divide your strings into array elements. The below example can split a string, where the word separator is either a comma or space:
<?php $MyString = 'development,programming design'; $keywords = preg_split("/[\s,]+/", $MyString); echo $keywords; // development echo $keywords; // programming echo $keywords; // design ?>