haitruonginfotech haitruonginfotech - 4 months ago 4
PHP Question

Error empty after use preg_match_all

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


Result is empty. How to fix working correctly

edit
editGroup

Answer

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