Find all PHP Variables with preg_match
\$(.*?)
Is not the right regular expression to match a PHP variable name. Such a regular expression for a Variable Name is actually part of the PHP manual and given as (without the leading dollar-sign):
[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
So in your case I'd try with:
\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)
instead then. See the following example:
<?php
/**
* Find all PHP Variables with preg_match
*
* @link http://stackoverflow.com/a/19563063/367456
*/
$pattern = '/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/';
$subject = <<<'BUFFER'
Hallo $var. blabla $var, $iam a var $varvarvar gfg djf jdfgjh fd $variable
BUFFER;
$result = preg_match_all($pattern, $subject, $matches);
var_dump($result);
print_r($matches);
Output:
int(5)
Array
(
[0] => Array
(
[0] => $var
[1] => $var
[2] => $iam
[3] => $varvarvar
[4] => $variable
)
[1] => Array
(
[0] => var
[1] => var
[2] => iam
[3] => varvarvar
[4] => variable
)
)
If you'd like to understand how regular expressions in PHP work, you need to read that in the PHP Manual and also in the manual of the regular expression dialect used (PCRE). Also there is a good book called "Mastering Regular Expressions" which I can suggest for reading.
See as well:
- PHP Syntax Regulary Expressed (Nov 2010; by hakre)
- PHP PCRE
- PCRE - Perl Compatible Regular Expressions