Reputation: 4432
How can I find all PHP variables with preg_match
. I made the following regular expression:
$string = 'Hallo $var. blabla $var, $iam a var $varvarvar gfg djf jdfgjh fd $variable';
$instring = array();
preg_match_all('/\$(.*?)/', $string, $instring);
print_r($instring);
I just don't understand how regular expressions work.
Upvotes: 7
Views: 12544
Reputation: 1502
Thanks for the answer by hakre. I combined it with a little bit more to also match PHP array variables and object oriented variables:
\$(([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(->)*)*(\[[^\]]*\])*)
That should match the following variables:
$this->that
$this["sure"]["thing"][0]
$var
$_GET["id"]
Upvotes: 1
Reputation: 1
To find all variables (including array variables) you can use regex (perl):
\$([a-zA-Z_\x7f-\xff]*)\[([a-zA-Z]{1}[a-zA-Z0-9_]{1,32})\]
then if you want to replace them including single quotes you replace them by:
\$$1['$2']
Upvotes: 0
Reputation: 11
Thank you very much for the answers, which helped me a lot.
Here's an elaborated version of the regex, expandig the finds to array-variables with at least numeric indices an a preceding logical negation:
function get_variables_from_expression($exp){
$pattern = '/((!\$|\$)[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*[0-9\[\]]*)/';
$result = preg_match_all($pattern,$exp,$matches);
return($matches[0]);
}
$example = '(($aC[5][7][1]xor((((!$a[5]&&!$a[4])&&!$a[3])&&!$a[2])&&$aC[6][6][0]))xor$aC[6][6][2])';
$list = get_variables_from_expression($example);
foreach($list as $var){
echo "$var<br>";
}
results in:
$aC[5][7][1]
!$a[5]
!$a[4]
!$a[3]
!$a[2]
$aC[6][6][0]
$aC[6][6][2]
Upvotes: 1
Reputation: 198237
\$(.*?)
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:
Upvotes: 22