Suppose I have this following string :
5+6-5*3/2+4
I need to split the string into two arrays: first array containing the integers, second array containing the operators from the string.
I have used the preg_split()
function, like this
preg_split("/[^0-9]+/", $str)
and have successfully completed the task, but I've been told to use the explode()
and implode()
functions. I tried using them, but now I'm totally confused about how to get the desired arrays using them.
Here preg_match
can also help you out. You can do it with preg_split
as well. preg_match
is a better solution if in case you have string like this 5+6-(5*3)/2+4
then preg_split
result also gives you (
and )
as well. Here we are using array_map
for iterating and preventing 0
's, which might get removed with array_filter
.
Try this code snippet here
Solution 1: using preg_match
Regex: (\d+)|([+-\/\*])
This will match either one or more digits or any arithmetic symbol.
<?php
ini_set('display_errors', 1);
$str = "5+6-5*3/2+4+0";
preg_match_all("/(\d+)|([+-\/\*])/", $str,$matches);
$digits=array();
array_map(function($value) use(&$digits){
if($value!=="" && $value!==null && $value!==false)
{
$digits[]=$value;
}
}, $matches[1]);
$symbols=array();
array_map(function($value) use(&$symbols){
if($value!=="" && $value!==null && $value!==false)
{
$symbols[]=$value;
}
}, $matches[2]);
print_r($digits);
print_r($symbols);
Try this code snippet here
Solution 2: using preg_split
Here we are spliting string on digits (\d+)
and symbols [+-\/\*]
<?php
ini_set('display_errors', 1);
$str = "5+6-5*3/2+4+0";
$symbols=preg_split("/(\d+)/", $str);
$digits=preg_split("/([+-\/\*])/", $str);
$symbols= array_filter($symbols);
print_r($digits);
print_r($symbols);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With