Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into array regex php

Tags:

arrays

regex

php

I need to split the string bellow into array keys like in this format:

string = "(731) some text here with number 2 (220) some 54 number other text here" convert into:

array( 
  '731' => 'some text here with number 2', 
  '220' => 'some 54 number other text here' 
);

I have tried:

preg_split( '/\([0-9]{3}\)/', $string ); 

and got:

array ( 
  0 => 'some text here', 
  1 => 'some other text here' 
); 
like image 482
Jeton R. Avatar asked Jul 29 '16 09:07

Jeton R.


People also ask

How Preg_match () and Preg_split () function works *?

How Preg_match () and Preg_split () function works *? preg_match – This function is used to match against a pattern in a string. It returns true if a match is found and false if no match is found. preg_split – This function is used to match against a pattern in a string and then splits the results into a numeric array.

What is Preg_split function in PHP?

The preg_split() function breaks a string into an array using matches of a regular expression as separators.

What is Preg_match_all in PHP?

The preg_match_all() function returns the number of matches of a pattern that were found in a string and populates a variable with the matches that were found.


1 Answers

Code

$string = "(731) some text here with number 2 (220) some 54 number other text here";

preg_match_all("/\((\d{3})\) *([^( ]*(?> +[^( ]+)*)/", $string, $matches);
$result = array_combine($matches[1], $matches[2]);

var_dump($result);

Output

array(2) {
  [731]=>
  string(28) "some text here with number 2"
  [220]=>
  string(30) "some 54 number other text here"
}

ideone demo


Description

The regex uses

  • \((\d{3})\) to match 3 digits in parentheses and captures it (group 1)
  • \ * to match the spaces in between keys and values
  • ([^( ]*(?> +[^( ]+)*) to match everything except a ( and captures it (group 2)
    This subpattern matches exactly the same as [^(]*(?<! ) but more efficiently, based on the unrolling-the-loop technique.

    *Notice though that I am interpreting a value field cannot have a ( within. If that is not the case, do tell and I will modify it accordingly.

After that, we have $matches[1] with keys and $matches[2] with values. Using array_combine() we generate the desired array.

like image 168
Mariano Avatar answered Oct 04 '22 06:10

Mariano