1

I try to split my string into an array. All strings between the calculation signs +/*-:

$keywords = preg_split("/[\s,-]*[+-*]+/", "quanity*price/2+tax");

This is what I try to achieve:

Array
(
    [0] => quantity
    [1] => price
    [1] => tax
)

But the result is an empty string.

10
  • 2
    Do you mean splitting on [-*\/+\d]+ regex101.com/r/3NEEfc/1 You could move the - to the beginning/end of the character class or escape it \- Commented Oct 17, 2019 at 14:04
  • 1
    oh, this is the website I really need. Thank you Commented Oct 17, 2019 at 14:05
  • No, but the fourth bird was offering it without asking Commented Oct 17, 2019 at 14:08
  • why not explode + str_replace here?? Commented Oct 17, 2019 at 14:10
  • 1
    @peace_love You could do it like this 3v4l.org/dmdHP Commented Oct 17, 2019 at 14:16

3 Answers 3

2

In the pattern you tried the second character class is not matching a digit and the hyphen should be escaped or placed at the beginning/end.

You could use a single character class instead. If you change the delimiter to other than / like ~ you don't have to escape the forward slash.

[-*\/+\d]+

Regex demo | Php demo

For example

$strings = [
    "quanity*price/2+tax",
    "quanity*price/2"
];

foreach ($strings as $string) {
    $keywords = preg_split("~[-*/+\d]+~", $string,  -1, PREG_SPLIT_NO_EMPTY);
    print_r($keywords);
}

Output

Array
(
    [0] => quanity
    [1] => price
    [2] => tax
)
Array
(
    [0] => quanity
    [1] => price
)

If you also want to match 0+ preceding whitespace chars, comma's:

[\s,]*[-*/+\d]+

Regex demo

Sign up to request clarification or add additional context in comments.

Comments

2

This will split the string where any of these exist: +/* and create an array out of it:

$string = "quanity*price/2+tax";  
$str_arr = preg_split ("/[-*\/+\d]+/", $string);  
print_r($str_arr); 

Posted code with your example for clarity.

Comments

1

Using the regex that The fourth bird recommended:

$keywords = preg_split("/[-*\/+\d]+/", "quanity*price/2+tax", -1, PREG_SPLIT_NO_EMPTY);

The PREG_SPLIT_NO_EMPTY should drop empty values (https://www.php.net//manual/en/function.preg-split.php).

2 Comments

The result of your answer: array:1 [▼ 0 => "quanity*price/2+tax" ]
Great catch, @peace_love. I'd missed the optional third parameter in preg_split and misplaced the flag. I've updated my answer to include -1 for the $limit parameter, to specify no limit. I could have also passed 0 or null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.