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'
);
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.
The preg_split() function breaks a string into an array using matches of a regular expression as separators.
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.
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.
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