Say I have the following string:
$str = "Hello, my name is Bob and I like 'pizza'. Do you like pizza??"
Currently I am able to split/explode this string on the whitespace using:
$arr = explode(' ', $str);
but I want to use the regex pattern \W
like so:
$arr = explode('\W', $str);
This should separate all words that aren't punctuation, allowing the 'pizza'
part to be separated as pizza
. Except it returns nothing (I get an empty array back).
What can I do?
The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.
The explode function is utilized to "Split a string into pieces of elements to form an array". The explode function in PHP enables us to break a string into smaller content with a break. This break is known as the delimiter.
Both are used to split a string into an array, but the difference is that split() uses pattern for splitting whereas explode() uses string. explode() is faster than split() because it doesn't match string based on regular expression.
PHP - Function split() The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.
Use preg_split:
http://www.php.net/manual/en/function.preg-split.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With