Php 在换行后剪切字符串

Php 在换行后剪切字符串,php,string,Php,String,我得到一个长字符串,并希望将其剪切成如下数组: "'1': '-' '2': CompanyA; 100EUR/Std '3': Company2; 100EUR/Std '4': Company B ; 155EUR/Std" 致: 可以在换行后剪切字符串吗?试试这个 $string = "'1': '-' '2': CompanyA; 100EUR/Std '3': Company2; 100EUR/Std '4': Company B ; 155EUR/Std" $a =

我得到一个长字符串,并希望将其剪切成如下数组:

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

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

试试这个

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

希望有帮助:)

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

$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\u match\u all
,您将获得组1中的所有键和组2中的值:

preg_match_all( $pattern, $string, $matches );
最后,使用
array\u combine
设置所需的键和值:

$result = array_combine( $matches[1], $matches[2] );
print_r( $result );
将打印:

数组
(
[1] => '-'
[2] =>公司;100欧元/标准
[3] =>公司2;100欧元/标准
[4] =>B公司;155欧元/标准
)

是将
'1:'
用作键还是仅用作普通键?您尝试过什么吗?数组的第一个值是正确的,或者它是一个输入错误(您在与其他键相反的键之后维护它)?创建新索引数组时,第一个键将从
0
可能的重复开始
$result = array_combine( $matches[1], $matches[2] );
print_r( $result );