• 6

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 187


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 187
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

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?

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");

This outputs:

  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.

  • 62
Reply Report

... 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."));

This blows into:

array(6) {
  string(9) "my string"
  string(17) "It contains text."
  string(11) "And several"
  string(12) "types of new"
  string(6) "lines."
  string(9) "And tabs."
  • 11
Reply Report
      • 1
    • This technique makes 6 passes over the input string (full traversal of the string x6) before exploding on the hyphen. I would be using the much simpler, single-function call in shamittomar's answer because it only makes one pass over the input string.