anon271334
anon271334

Reputation:

Split a string in half by a delimiting character

I am trying to split a string in PHP however it's not as easy as it is in C#, it seems to be a tad bit messy...

I have a string, which looks something like this:

blahblah1323r8b|7.45

and I would like to be able to access the results of the split like this:

$var = split_result['leftside'];
$var = split_result['rightside'];

Is this easy to do in PHP? I'm trying to find some good examples, but the ones I've seen seem to be not what I'm trying to do, and are a little over complicated.

Upvotes: 0

Views: 2655

Answers (2)

mickmackusa
mickmackusa

Reputation: 48049

PHP has adopted a C language function sscanf() for parsing a predictably formatted string AND it has the capability of casting the numeric values as integer/float types (which explode() can't do by itself).

A few implemenations depending on your needs: (Demo)

  1. return an array:

    var_export(
        sscanf($str, '%[^|]|%f')
    );
    

    output:

    array (
      0 => 'blahblah1323r8b',
      1 => 7.45,
    )
    
  2. create individual variables:

    sscanf($str, '%[^|]|%f', $left, $right);
    var_dump($left, $right);
    

    output:

    string(15) "blahblah1323r8b"
    float(7.45)
    
  3. create an associative array:

    [$key, $result[$key]] = sscanf($str, '%[^|]|%f');
    var_export($result);
    

    output:

    array (
      'blahblah1323r8b' => 7.45,
    )
    

Upvotes: 0

casablanca
casablanca

Reputation: 70731

To get an array:

$array = explode('|', $str);

Or to directly get two parts:

list($left, $right) = explode('|', $str);

See explode in the PHP manual.

Upvotes: 12

Related Questions