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.
The preg_match() function returns whether a match was found in a string.
Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .
preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.
Regular expressions are commonly known as regex. These are nothing more than a pattern or a sequence of characters, which describe a special search pattern as text string. Regular expression allows you to search a specific string inside another string.
\$(.*?)
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With