我需要将字符串拆分为数组键,如下所示:
string = "(731) some text here with number 2 (220) some 54 number other text here"转换为:
array(
'731' => 'some text here with number 2',
'220' => 'some 54 number other text here'
);
Run Code Online (Sandbox Code Playgroud)
我试过了:
preg_split( '/\([0-9]{3}\)/', $string );
Run Code Online (Sandbox Code Playgroud)
得到了:
array (
0 => 'some text here',
1 => 'some other text here'
);
Run Code Online (Sandbox Code Playgroud)
码
$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);
Run Code Online (Sandbox Code Playgroud)
产量
array(2) {
[731]=>
string(28) "some text here with number 2"
[220]=>
string(30) "some 54 number other text here"
}
Run Code Online (Sandbox Code Playgroud)
描述
正则表达式使用
\((\d{3})\) 匹配括号中的3位数并捕获它(组1)\ * 匹配键和值之间的空格([^( ]*(?> +[^( ]+)*)匹配除a以外的所有内容(并捕获它(组2)
此子模式[^(]*(?<! )基于展开循环技术完全匹配但更有效.
*注意虽然我正在解释一个值字段不能有一个(内部.如果不是这样,请告诉我,我会相应地修改它.
在那之后,我们有了$matches[1]键和$matches[2]值.使用array_combine()我们生成所需的数组.
| 归档时间: |
|
| 查看次数: |
1041 次 |
| 最近记录: |