我有以下文本:
$string='
blah<br>
@include (\'file_to_load\')
<br>
@include (\'file_to_load\',\'param1\',\'param2\',\'param3\')
';
我希望能够捕获所有带参数的"@include"出现,并使用preg_replace_callback函数进行替换 (例如:@include ('file_to_load','param1','param2','param3'))。
因此,我这样做:
$string='
blah<br>
@include (\'file_to_load\')
<br>
@include (\'file_to_load\',\'param1\',\'param2\')
';
$params=[];
$result = preg_replace_callback(
'~@include \((,?.*?)\)~',//I catch @include, parenthesis and all between them
function ($matches) {
echo '---iteration---';
$params=explode(',',$matches[1]);//exploding by a comma
echo '<pre>';
var_dump($params);
echo '</pre>';
return $matches[1];
},
$string
);
一切都很好,直到逗号出现在参数内部,就像这样:
$string='
blah<br>
@include (\'file_to_load\')
<br>
@include (\'file_to_load\',\'param1,something\',[\'elem\'=>\'also, a comma\']])
';
这里我们有一个逗号在“param1”参数内部,现在,在使用explode()函数分割后,它显然不能按照我想要的方式工作。
有没有一种方法可以通过正则表达式将字符串按逗号分割,但不在单引号内时进行分割?
str_getcsv
比重新发明它要简单。 - mario