Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple explode characters with comma and - (hyphen)

I want to explode a string for all:

  1. whitespaces (\n \t etc)
  2. comma
  3. hyphen (small dash). Like this >> -

But this does not work:

$keywords = explode("\n\t\r\a,-", "my string");

How to do that?

like image 775
WhatIsOpenID Avatar asked Sep 09 '10 17:09

WhatIsOpenID


People also ask

What does the explode () function do?

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.

Which one is syntax for explode function?

PHP | explode() Function separator : This character specifies the critical points or points at which the string will split, i.e. whenever this character is found in the string it symbolizes end of one element of the array and start of another.


2 Answers

Explode can't do that. There is a nice function called preg_split for that. Do it like this:

$keywords = preg_split("/[\s,-]+/", "This-sign, is why we can't have nice things"); var_dump($keywords); 

This outputs:

  array   0 => string 'This' (length=4)   1 => string 'sign' (length=4)   2 => string 'is' (length=2)   3 => string 'why' (length=3)   4 => string 'we' (length=2)   5 => string 'can't' (length=5)   6 => string 'have' (length=4)   7 => string 'nice' (length=4)   8 => string 'things' (length=6) 

BTW, do not use split, it is deprecated.

like image 197
shamittomar Avatar answered Oct 02 '22 16:10

shamittomar


... or if you don't like regexes and you still want to explode stuff, you could replace multiple characters with just one character before your explosion:

$keywords = explode("-", str_replace(array("\n", "\t", "\r", "\a", ",", "-"), "-", 
  "my string\nIt contains text.\rAnd several\ntypes of new-lines.\tAnd tabs."));
var_dump($keywords);

This blows into:

array(6) {
  [0]=>
  string(9) "my string"
  [1]=>
  string(17) "It contains text."
  [2]=>
  string(11) "And several"
  [3]=>
  string(12) "types of new"
  [4]=>
  string(6) "lines."
  [5]=>
  string(9) "And tabs."
}
like image 37
Florian Mertens Avatar answered Oct 02 '22 18:10

Florian Mertens