简体   繁体   中英

Cut String after word wrap

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?

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
)

regex101 demo

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM