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

Suppose I have the following line:

5+6-5*3/2+4 

I need to split a string into two arrays: the first array containing integers, the second array containing operators from the string.

I used the preg_split() function, like this

 preg_split("/[^0-9]+/", $str) 

and successfully completed the task, but they told me to use the functions explode() and implode() . I tried using them, but now I'm completely confused about how to use the arrays they need.

+5
source share
5 answers

Here preg_match can also help you. You can do this with preg_split . preg_match is the best solution, if you have a line like this 5+6-(5*3)/2+4 , then the result of preg_split also gives you ( and ) . Here we use array_map to iterate and prevent 0 , which can be removed with array_filter .

Try this piece of code here

Solution 1: using preg_match

Regex: (\d+)|([+-\/\*]) This will match one or more digits or any arithmetic character.

 <?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 piece of code here

Solution 2: using preg_split

Here we divide the string into numbers (\d+) and characters [+-\/\*]

 <?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); 
+9
source

Try this job for me

First method

 $str = "5+6-5*3/2+4"; preg_match_all('!\d+!', $str, $matches); preg_match_all('/[^0-9]+/', $str, $matches2); print_r($matches[0]); //integers echo '<br/>'; print_r($matches2[0]); //operators 

Second method

 function multiexplode ($delimiters,$string) { $ready = str_replace($delimiters, $delimiters[0], $string); $launch = explode($delimiters[0], $ready); return $launch; } $resultArray = multiexplode(array('+','-','/','*'), $str); print_r($resultArray); echo '<br/>'; $resultArray1 = array_filter(multiexplode(range(0,9), $str)); print_r($resultArray1); 
+1
source

A regular expression solution is the only reasonably effective way to extract the required substrings from the input string.

With the capture of numbers, four main patterns to choose from: \d+ , [0-9]+ , [^\*-\/]+ , [^+\-\*\/]+ All four patterns take an equal number of "steps", Therefore, the decisive factor is the pattern of brevity and \d+ wins.

When capturing characters, there are four main patterns: [^\d] , [^0-9] , [\*-\/] , [+-\/\*] All four patterns take an equal number of "steps", so the deciding factor is the brevity of the chart and [^\d] wins.

For both of my methods, I will use $str="50+16-0*387/2+49"; as my input, since it includes zero and multi-valued integers.

Below is the Demo for both of my methods below.


A CLEAN TWO-LINER :

This improves the second Sahil method by implementing the shortest patterns, removing the brackets to capture, using null for unlimited separation, and tagging with PREG_SPLIT_NO_EMPTY to preg_split () ):

 $digits=preg_split("/[^\d]/",$str,null,PREG_SPLIT_NO_EMPTY); $symbols=preg_split("/\d+/",$str,null,PREG_SPLIT_NO_EMPTY); // leaving NO_EMPTY flag in place though it would only come into play if the string began or ended with a symbol (like say, "-5+3" or something) 

Note. Bachcha Singh uses a similar two-line approach using preg_match_all() , but this is slightly less efficient because it generates a true / false boolean value in addition to a multidimensional array, where when my preg_split() method just generates a one-dimensional array.


LESS READ ONE LINE :

I also wrote a one-line solution as a personal call that uses: array_map () , preg_split() and is_numeric () :

 array_map(function($v)use(&$digits,&$symbols){is_numeric($v)?$digits[]=$v:$symbols[]=$v;},preg_split("/(\d+|[^\d])\K/",$str,null,PREG_SPLIT_NO_EMPTY)); 

Here is a breakdown on several lines:

 array_map( // iterate each value in the input array function($v)use(&$digits,&$symbols){ // $v is each value; declare output arrays as modifiable is_numeric($v)? // evaluate the value as a number $digits[]=$v: $symbols[]=$v; }, preg_split( // use a regex pattern to explode a string "/(\d+|[^\d])\K/", // split on each match, but \K stops the match being removed $str, // the input string null, // make unlimited splits PREG_SPLIT_NO_EMPTY // do not include any empty pattern matches ) ); 

Both methods will create the corresponding arrays:

 array('50','16','0','387','2','49') array('+','-','*','/','+') 
+1
source

Try i send another method

 <?php error_reporting(0); $str = "5+6-5*3/2+4"; $array_opartor=preg_split("/[0-9]/", $str); $array_integer=preg_split("/[^0-9]+/", $str); $two_array=array_merge($array_opartor,$array_integer); $all_operator=array(); $all_numeric=array(); foreach($two_array as $array_results) { if(is_numeric($array_results)) { array_push($all_numeric,$array_results); } else if($array_results!="") { array_push($all_operator,$array_results); } } print_r($all_operator); // View All operator in array echo "<br/>"; print_r($all_numeric); // View All Numeric value in Array ?> 

Second solution

 <?php error_reporting(0); $str = "5+6-5*3/2+4"; $array_opartor=preg_split("/[0-9]/", $str); $array_integer=preg_split("/[^0-9]+/", $str); $all_operator=array_filter($array_opartor);//use thi fo remove all null value in array print_r($all_operator); // View All operator in array echo "<br/>"; print_r($array_integer); // View All Numeric value in Array ?> 
0
source

I like the method implemented by @Sahil Gulati, but it does not meet your requirements for using explode-implode.

Here is my code for this:

 function solution5($S){ $return['digits'] = multipleExplode(array('+','-','/','*'), $S); $return['symbols']= array_filter(multipleExplode(range(0,9), $S)); return $return; } function multipleExplode($del,$str) { $passStr = str_replace($del, $del[0], $str); $returnArr = explode($del[0], $passStr); return $returnArr; } var_dump(solution5("5+6-5*3/2+4")); 

Perhaps this will help you solve your request.

0
source

Source: https://habr.com/ru/post/1267128/


All Articles