On 4 Feb 2005 08:48:38 -0800, hu8 <ja*****************@hotmail.com> wrote:
I must find a regular expression to find every declaration af a
variable in a php programm.....
I tried:
/\$([a-zA-0-9_])*(\s|\S)\=(\s|\S)/is
But it doesn't reall go :-(
I've got no expreience in things like regular expressions...
And: Is it possible to look if the decaration ist in ' or " ?? If eyes:
how and if no :-@
You could do it this way:
preg_match_all('/$\s*\$([\w\d_]+)\s*=\s*(\'|"|)?(.*?)(?<!\\\)\\2;/ms',$text,$match);
'/$\s*\$ #Match from beginning of line, any number of whitespace
(indents), until a $ is met.
([\w\d_]+) #Store variable name in $match[1].
\s*=\s* #any number of whitespace, equal sign and whitespace again.
(\'|"|) #Store any optional ', " or nothing in $match[2].
(.*?) #Store variable value in $match[3]
(?<!\\\)\\2 #Until we meet the value we found in $match2, which again must
not be escaped.
; #And finally the ;
/ms #Multiline, and dotall modifiers.
Code example:
<?php
$text = '
$test1 = "test \"; test";
$test2 = "test2";
if($test2 = "test2") {
$test3 = \'test\';
}
if(isset($test3)) {
print "$test";
}
$test4 = 5;
$test5 = $test1;
';
preg_match_all('/$\s*\$([\w\d_]+)\s*=\s*(\'|"|)?(.*?)(?<!\\\)\\2;/ms',$text,$match);
print_r($match);
?>
will result in:
[1] => Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
[4] => test5
)
[2] => Array
(
[0] => "
[1] => "
[2] => '
[3] =>
[4] =>
)
[3] => Array
(
[0] => test \"; test
[1] => test2
[2] => test
[3] => 5
[4] => $test1
)
This code isn't 100%, but will work most of the time I think.
Double escapes in front of quotes wil mess things up a bit.
If thats a problem you may edit the (?<!\\\) part to something
like (?<!\\\\\\\\\|\\\), but thats just ugly, and in most cases
not nescessary.
Hope this helps.
--
Stian Berger