Reputation: 135
How can I place a variable inside a function when it is run in order to preg_match the right information. Here is my existing code:
$username = "test";
function is_txt($file) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
What I am attempting to do is pull the $username variable from outside the function and allow it to be seen within it so I can pull the right matches in my while loop. While the previous comes back blank, if i do the following it works:
$username = "test";
function is_txt($file) {
$username = "test";
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
Upvotes: 1
Views: 45
Reputation: 32953
You need to import the var with global
:
function is_txt($file) {
global $username;
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9] {2}_'.$username.'.tar.gz/', $file) > 0;
}
But passing the value in as a parameter as explained by Jonah is a better solution in most cases.
Upvotes: 1
Reputation: 12581
Modify the function to take the $username
variable as a parameter:
function is_txt($file, $u) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$u.'.tar.gz/', $file) > 0;
}
Then call it like:
$username = "test";
is_txt($file, $username);
Alternatively, you can use the global
keyword to make the variable visible from the function. This is sometimes useful, but shouldn't be used all over the place. See the variable scope manual entry for more info.
Upvotes: 2