Reputation: 4187
I have a file test.php:
public function editAction() {
//...
}
public function editGroupAction() {
//...
}
This is my code:
$source = "test.php";
$fh = fopen($source,'r');
while ($line = fgets($fh)) {
preg_match_all('/function(.*?)Action()/', $line, $matches);
var_dump($matches);
}
I want to get the functions that end with Action
, but the result is empty. How do I get a result like this:
edit
editGroup
Upvotes: 0
Views: 228
Reputation: 6215
Your code can be simplified to this:
$fileName = 'test.php';
$fileContent = file_get_contents($fileName);
preg_match_all('/function(.*?)Action()/', $fileContent, $matches);
$functions = $matches[1];
Result ($functions
):
Array
(
[0] => edit
[1] => editGroup
)
Following is your code with some changes...
First, check if anything was found, if so, add that to an array. Here is the working code:
$source = "test.php";
$fh = fopen($source,'r');
$m = array();
while ($line = fgets($fh)) {
if(preg_match_all('/function(.*?)Action()/', $line, $matches)){
$m[] = $matches[1][0];
}
}
Result ($m
):
Array
(
[0] => edit
[1] => editGroup
)
Since preg_match_all returns the number of full pattern matches, you can use the return to check if anything was found. If you get a hit, add the wanted value to an array so you can get it later.
You were getting some empty results because not all lines will match ;)
Sidenote: As mentioned, you'll end up with something like string(5) " edit"
(notice the white space). I don't know preg, so I can't fix it for you. What I can do is suggest you to change to $functions = array_map('trim', $matches[1]);
Upvotes: 2
Reputation: 2555
Not sure if that's what you want, but you should escape parentheses in regexp.
So here's your code with minor modifications:
<?php
$content = "public function editAction() public function editGroupAction()";
preg_match_all('/function(.*?)Action\(\)/', $content, $matches);
echo '<pre>';
var_dump($matches);
echo '</pre>';
?>
And yes, result is not empty :)
Upvotes: 0