php - Split Up String With Two Conditions: "+" and "-" And Keep Signs


Keywords:php 


Question: 

I am using PHP and am trying to split up a string such as this: 3x^3 - 4x^2 + 2x - 3 + 5x^5 - 2x^7 between all the - (minus) and + (plus) symbols. I have tried using explode(), but this can only accept one condition (only - or +, not both).

I have looked at the preg_split() function, and have tried using "/+|-/" as the regular expression for the first condition, but it does not work because + is not treated as the character "+", but as an operator for regex. How could I split up the string between - and + using proper regex?

UPDATE: Sahil Gulati, thank you for your response. The regular expression you posted worked perfectly. However, after reading symcbean's comment, I realized I also need to keep the signs. How would I accomplish this?


2 Answers: 

You should escape + character by using this \+, Here you can use either this /\+|\-/ or /[\+\-]/ here both regex means either + and -

<?php

ini_set('display_errors', 1);
$string='3x^3 - 4x^2 + 2x - 3 + 5x^5 - 2x^7';
$segments=preg_split("/\+|\-/", $string);
print_r($segments);
 

After reading your question update, it appears that you can go back to explode() on each empty space.

Here is the one-liner:

$string='3x^3 - 4x^2 + 2x - 3 + 5x^5 - 2x^7';
var_export(explode(' ',$string));

Output:

array (
    0 => '3x^3',
    1 => '-',
    2 => '4x^2',
    3 => '+',
    4 => '2x',
    5 => '-',
    6 => '3',
    7 => '+',
    8 => '5x^5',
    9 => '-',
    10 => '2x^7'
)