I have the following text:
$string='
blah<br>
@include (\'file_to_load\')
<br>
@include (\'file_to_load\',\'param1\',\'param2\',\'param3\')
';
I'd like to catch (and then replace using preg_replace_callback) all the occurences of "@include" with parameters (e.g. @include ('file_to_load','param1','param2','param3') )
So I do this:
$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
);
And everything's fine until a comma appears inside a parameter, like here:
$string='
blah<br>
@include (\'file_to_load\')
<br>
@include (\'file_to_load\',\'param1,something\',[\'elem\'=>\'also, a comma\']])
';
Here we have a comma inside a "param1" param, now, after exploding with the explode() function it obviously doesn't work like I want.
I there a way to explode() (by using regular expression probably) the string by a comma, but not when the comma is inside apostrophes?
Use the following to split:
,(?=([^']*'[^']*')*[^']*$)
Use preg_split since explode does not support regex:
Code:
$params = preg_split(',(?=([^']*'[^']*')*[^']*$)',$matches[1]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With