Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into two arrays using explode-implode functions?

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.

like image 760
Tango Alpha Avatar asked Apr 25 '17 10:04

Tango Alpha


1 Answers

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);
like image 158
Sahil Gulati Avatar answered Nov 14 '22 21:11

Sahil Gulati