Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - how to explode a string using a comma, except situtation when this comma is inside apostrophes?

Tags:

regex

php

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?

like image 843
konrados Avatar asked Nov 27 '25 05:11

konrados


1 Answers

Use the following to split:

,(?=([^']*'[^']*')*[^']*$)

Use preg_split since explode does not support regex:

Code:

$params = preg_split(',(?=([^']*'[^']*')*[^']*$)',$matches[1]);
like image 83
karthik manchala Avatar answered Nov 29 '25 20:11

karthik manchala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!