Thursday, April 28, 2011

Split String into Parts PHP

Have the following string i need to split.

$string = "This is string sample - $2565";
$split_point = " - ";

One: I need to be able to split the string into two parts using a regex or any other match and specify where is going to split.

Second: Also want to do a preg_match for $ and then only grab number on the right of $.

Any suggestions?

From stackoverflow
  • $split_string = explode($split_point, $string);
    

    and

    preg_match('/\$(\d*)/', $split_string[1], $matches);
    $amount = $matches[1];
    

    If you want, this could all be done in one regex with:

    $pattern = '/^(.*)'.preg_quote($split_point).'\$(\d*)$/'
    
    preg_match($pattern, $string, $matches);
    $description = $matches[1];
    $amount = $matches[2];
    
    Wimmer : Please, to avoid unexpected errors, do add preg_quote around the $split_point in the regex example.
  • $parts = explode ($split_point, $string);
    /*
    $parts[0] = 'This is string sample'
    $parts[1] = '$2565'
    */
    
  • Two other answers have mentioned explode(), but you can also limit the number of parts it's meant to split your source string into. For instance:

    $s = "This is - my - string.";
    list($head, $tail) = explode(' - ', $s, 2);
    echo "Head is '$head' and tail is '$tail'\n";
    

    Will given you:

    Head is 'This is' and tail is 'my - string.'
    
    Codex73 : Isn't the output: Head is 'This is-' and tail is 'my - string.' ?
    Keith Gaughan : Nope, definitely not. I even checked it in the PHP REPL before posting.
    Codex73 : so what happened to the first - ?
    Codex73 : your completely right. I forgot you exploded " - " and not "-".
    Codex73 : how will i split from the last - and not the first. can i make explode search from right to left instead?
    Keith Gaughan : There's no simple way to do that, mainly because it's not something you usually want to do. Unfortunately, the intuitive way of doing it (using a negative number) does something completely different. Try exploding the string, popping the last element, and imploding it again.
  • explode is the right solution for your specific case, but preg_split is what you want if you ever need regular expressions for the separator :)

0 comments:

Post a Comment