1

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.

3
  • Try single quotes round your $pattern. Commented Mar 6, 2021 at 15:03
  • Dear Nigel Ren, It works with single quotes, but if I use: '/\$(?<name>.+?) = '(?<value>.+?)';/' it not works. Commented Mar 6, 2021 at 15:09
  • use : $pattern = '/\$(?<name>.+?) = (?<value>.+?);/'; Commented Mar 6, 2021 at 15:21

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.