Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert string to array character

Tags:

php

The first line of code is converted to the second code. I can use the padding methods, but I want to get the solution from the shortest path and convert it quickly. I will use the code field in the sql select section

 $it = "(a(am,bam),b(dam,cam))";
 $to = "a.am, a.bam, b.dam, b.cam";
like image 547
Hamza Özkan Avatar asked Sep 19 '26 23:09

Hamza Özkan


1 Answers

Try following code:

$it = "(a(am,bam),b(dam,cam))";

function iDelimiter( $str ) {

    $count = 0;
    $str = str_split( $str );

    foreach( $str as &$value ) {

        if( $value == "(" ) {
            $count++;
        } elseif( $value == ")" ) {
            $count--;
        }

        if( $value == "," && ! $count ) {
            $value = "|";
        }

    }

    return explode( "|", implode( $str ) );

}

function iParser( $str, $_prefix = "" ) {

    preg_match( "/^((?!(\(|\))).)*\((.*)\)$/", $str, $m );

    if( count( $m ) < 4 ) {
        return ( strlen( $_prefix ) ? $_prefix . "." : '' ) . $str;
    }

    $prefix = ( strlen( $_prefix ) ? $_prefix . "." : '' ) . $m[1];

    $str = $m[3];

    if( strpos( $str, "(" ) === false ) {

        $return = explode( ",", $str );

        $pad = preg_filter( '/^/', strlen( $prefix ) ? $prefix . '.' : '', $return );

        return implode( $pad, "," );
    } else {

        $str = iDelimiter( $str );

        $return = array_map( 'iParser', $str, array_pad( array(), count( $str ), $prefix ) );

        return implode( $return, ", " );
    }

}

print_r( iParser( $it ) );

It parse every depth of parentheses. Just pass your string to iParser function.

like image 189
MahdiY Avatar answered Sep 22 '26 12:09

MahdiY