Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP预匹配模式[var1]var2_Php_Preg Match_Preg Match All - Fatal编程技术网

PHP预匹配模式[var1]var2

PHP预匹配模式[var1]var2,php,preg-match,preg-match-all,Php,Preg Match,Preg Match All,我正试着从preg_match开始,但我没有找到正确的模式 字符串看起来像[abc]def[ghi]jul[mno]pqr 我需要类似于数组的东西(abc=>def,ghi=>jul,mno=>pqr) 有什么想法吗?试试这个正则表达式 /\[([a-z]+)\]( [a-z]+)?/ 在preg\u match\u all()中 在那次尝试之后 $regex = '/\[([a-z]+)\][ ]?([a-z]+)?/'; $string = '[abc] def [ghi] jul [mn

我正试着从preg_match开始,但我没有找到正确的模式

字符串看起来像
[abc]def[ghi]jul[mno]
pqr

我需要类似于
数组的东西(abc=>def,ghi=>jul,mno=>pqr)

有什么想法吗?

试试这个正则表达式

/\[([a-z]+)\]( [a-z]+)?/
preg\u match\u all()中

在那次尝试之后

$regex = '/\[([a-z]+)\][ ]?([a-z]+)?/';
$string = '[abc] def [ghi] jul [mno] pqr';

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

$arr = array();

foreach($matches[1] as $index => $match){
    $arr[$match] = $matches[2][$index];
}

print_r($arr);
您可以为
$matches[2][$index]
添加
isset()
,但我认为我的代码也可以使用


@MateiMihai建议
$result=array\u combine($matches[1],$matches[2])

向我们展示您的努力。我们不是来给你做作业的!!!我试过一些例子,但我不知道这到底是怎么回事。@mrmow让我看看我的答案,如果我的代码不起作用,你想说什么。[(.*)(*))只对一个有效
*
非常慢。用于简单的
[^\]
而不是
*
。那么
\[([a-z]+)\](\s[a-z]+)?
呢?使用空格而不是
\s
确实是一种不好的做法。您肯定不想捕获空格吗
\[([a-z]+)\](?:[\s]?)([a-z]+)?
@ling.s@Ankh但是
\s
也捕获新行和其他行:我将使用
$result=array\u组合($matches[1],$matches[2])而不是那个foreach