自动换行后剪切字符串


Cut String after word wrap

我得到一个长字符串,想把它们切成这样的数组:

"'1': '-'
 '2': CompanyA; 100EUR/Std
 '3': Company2; 100EUR/Std
 '4': Company B ; 155EUR/Std"

自:

array(
 1 => '-',
 2 => 'CompanyA; 100EUR/Std',
 3 => 'Company2; 100EUR/Std',
 4 => 'Company B ; 155EUR/Std'
);

可以在自动换行后剪切字符串吗?

为此必须使用正则表达式模式:

$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
";

然后,使用 preg_match_all ,您将获得组 1 中的所有键和组 2 中的值:

preg_match_all( $pattern, $string, $matches );

最后,使用 array_combine 设置所需的键和值:

$result = array_combine( $matches[1], $matches[2] );
print_r( $result );

将打印:

Array
(
    [1] => '-'
    [2] => CompanyA; 100EUR/Std
    [3] => Company2; 100EUR/Std
    [4] => Company B ; 155EUR/Std
)

正则表达式101演示

试试这个

$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);

希望对:)有所帮助