How to split a string by multiple delimiters in PHP?

42,062

Solution 1

<?php

$pattern = '/[;,]/';

$string = "something here ; and there, oh,that's all!";

echo '<pre>', print_r( preg_split( $pattern, $string ), 1 ), '</pre>';

Solution 2

$result_array = preg_split( "/[;,]/", $starting_string );

Solution 3

The split() PHP function allows the delimiter to be a regular expression. Unfortunately it's deprecated and will be removed in PHP7!

The preg_split() function should be OK, and it returns an array:

$results = preg_split('/[;,]/', $string);

There are a few extra optional parameters which may be useful to you.

Is the first delimiter character in your edited example actually a 2 byte Unicode character?

Perhaps the preg_slit() function is treating the delimiter as three characters and splitting between the characters of the unicode (Chinese?) 'character'

Share:
42,062
omg
Author by

omg

Updated on May 24, 2020

Comments

  • omg
    omg almost 4 years

    "something here ; and there, oh,that's all!"

    I want to split it by ; and ,

    so after processing should get:

    something here
    
    and there
    
    oh
    
    that's all!
    
  • user3167101
    user3167101 over 14 years
    If you want print_r() to return a string to be echo'd, the proper way to do it is to pass in a 2nd argument that evaluates to true. e.g. print_r($array, true);
  • JCC
    JCC over 14 years
    Shouldn't the commas after the '<pre>' be periods, instead?
  • meder omuraliev
    meder omuraliev over 14 years
    @EvilChookie: I'm sending multiple arguments, I'm just used to doing it that way.
  • user3167101
    user3167101 over 14 years
    @EvilChookie - they even say it's faster to send multiple arguments then to concatenate. However, I'd think the difference would be minimal. Feel free to prove me wrong!
  • meder omuraliev
    meder omuraliev over 14 years
    Call me nuts but personally it's just faster to use my middle finger and hit the comma than my ring finger on the period, the speed difference between multiple arguments and concatenation is probably so minimal that you'll never notice unless you're doing multiple nested loops or something of that nature, it's possible there won't even be a noticeable difference then.
  • omg
    omg over 14 years
    Hey buddy,there is some tiny issue with your solution,see my update:)
  • meder omuraliev
    meder omuraliev over 14 years
    What character is that? That's not a semicolon.
  • meder omuraliev
    meder omuraliev over 14 years
    Check out my updated version, I found the unicode equivalent for that character.
  • omg
    omg over 14 years
    The code is the same as your update.Let me open another question anyway:)
  • JCC
    JCC over 14 years
    I just wasn't sure if it was a typo, or if that were actually a proper way to perform an echo (which it clearly is). Thanks for clarifying :P