Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's up with PHP explode() patterns?

Tags:

regex

php

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?

like image 942
Alex Avatar asked Jul 14 '11 13:07

Alex


People also ask

What does explode () do in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.

Why explode () is used?

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.

What is the difference between explode and split?

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.

What is split in PHP?

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.


1 Answers

Use preg_split:

http://www.php.net/manual/en/function.preg-split.php

like image 148
Frunsi Avatar answered Oct 01 '22 17:10

Frunsi