Search code examples
phpstringsplit

Split string in half by a delimiting substring


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 $.


Solution

  • $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];