0

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
4
  • 1
    Result is not empty, see here : eval.in/612829 --- EDIT : Too slow, guess @FirstOne deserves his nickname. Commented Jul 27, 2016 at 13:32
  • As for the question: make sure your code is the same as the one you posted. Commented Jul 27, 2016 at 13:36
  • 1
    It's worth noting that you'll still have a space at the beginning of your outputs, you should escape that as well. Commented Jul 27, 2016 at 13:39
  • I had edit question again Commented Jul 27, 2016 at 13:40

2 Answers 2

2

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]);

Sign up to request clarification or add additional context in comments.

Comments

0

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 :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.