peace_love
peace_love

Reputation: 6471

How can I split a string into an array?

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.

Upvotes: 1

Views: 129

Answers (3)

Josh
Josh

Reputation: 254

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

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163362

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

Upvotes: 2

Mathal
Mathal

Reputation: 55

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.

Upvotes: 2

Related Questions