Reputation: 125
I get a long string and want to cut them into an array like this:
"'1': '-'
'2': CompanyA; 100EUR/Std
'3': Company2; 100EUR/Std
'4': Company B ; 155EUR/Std"
to:
array(
1 => '-',
2 => 'CompanyA; 100EUR/Std',
3 => 'Company2; 100EUR/Std',
4 => 'Company B ; 155EUR/Std'
);
Is it possible to cut a String after a word wrap?
Upvotes: 1
Views: 174
Reputation: 11689
You must use a regular expression pattern for this:
$pattern =
"
~
^ # start of line
' # apostrophe
(\d+) # 1st group: one-or-more digits
':\s+ # apostrophe followed by one-or-more spaces
(.+) # 2nd group: any character, one-or-more
$ # end of line
~mx
";
Then, with preg_match_all
, you will obtain all the keys in group 1 and the values in group 2:
preg_match_all( $pattern, $string, $matches );
At the end, use array_combine
to set desired keys and values:
$result = array_combine( $matches[1], $matches[2] );
print_r( $result );
will print:
Array
(
[1] => '-'
[2] => CompanyA; 100EUR/Std
[3] => Company2; 100EUR/Std
[4] => Company B ; 155EUR/Std
)
Upvotes: 2
Reputation: 1777
try this
$string = "'1': '-'
'2': CompanyA; 100EUR/Std
'3': Company2; 100EUR/Std
'4': Company B ; 155EUR/Std"
$a = explode(PHP_EOL, $string);
foreach ($a as $result) {
$b = explode(':', $result);
$array[$b[0]] = $b[1];
}
print_r($array);
hope it helps :)
Upvotes: 1