PHP string convert

I’m sorry, but I speak a little English.

I use:

$file = file_get_content ( 'cfg.php' );

The cfg.php file example:

$pw = 'abcdefgh';
$user = 12345678;

I would like convert to string this PHP file, because I would like use:

$pattern = "/$(?<name>.+?) = '(?<value>.+?)';/";

if ( preg_match_all ( $pattern, $file, $matches ) ) {

    foreach ( $matches [ 'name' ] as $key => $value ) {

        print $value . ' = ' . $matches [ 'value' ] [ $key ] . '<br>';

    }

} else {}

I would like see:

pw = abcdefgh
user = 12345678

I think the problem is the dollar $ signs because run PHP, but I would like no PHP, only string the $file.

Please help me, thanks.

Answer

You have to multiple escape the backslashes:

$file =<<<'EOD'
$pw = 'abcdefgh';
$user = 12345678;
EOD;

$pattern = "/\$(?<name>.+?) = ('?)(?<value>.+?)\2;/";
if ( preg_match_all ( $pattern, $file, $matches ) ) {
    foreach ( $matches [ 'name' ] as $key => $value ) {
        print $value . ' = ' . $matches [ 'value' ] [ $key ] . '<br>';
    }
}

Output:

pw = abcdefgh<br>user = 12345678<br>

Leave a Reply

Your email address will not be published. Required fields are marked *