How do you split a string into an array?
Use explode() to split a string into an array at a separator, like a comma. Here the extra spaces after the commas are removed with trim().
<?php
$languages = "PHP, HTML, CSS, JavaScript, MySQL";
$list = array_map("trim", explode(",", $languages));
print_r($list);
?>
Output:
Tutorials Class - Output Window
Array
(
[0] => PHP
[1] => HTML
[2] => CSS
[3] => JavaScript
[4] => MySQL
)
To split a string into single characters use str_split(). To split by a pattern (like many spaces) use preg_split().
<?php
echo json_encode(str_split("PHP")) . "<br>";
echo json_encode(preg_split("/\s+/", "one two three"));
?>
Output:
Tutorials Class - Output Window
[“P”,”H”,”P”]
[“one”,”two”,”three”]
Learn more in PHP explode() Function.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP String Handling |
| PHP explode() Function |
| PHP strpos() Function |
| PHP implode() Function |