I am trying to search a log file for a pattern using preg_match_all however the regex doesn't seem to be working quite right. It saying no matches
Here is a sample line from the log file
04:19:58 | Player "xxx" (id=xxx pos=<3748.4, 5976.5, 403.3>)
I am trying to search for the pos=< > and store the values in an array but I also need the other content on the line
$contents = file_get_contents('logs/'.$log);
$pattern = '/pos=<(.*?),(.*?),(.*?)>/m';
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
CodePudding user response:
Try this regex
$pattern = '/pos\=\<(.*?)\,(.*?)\,(.*?)\>/m';
Use regex debuggers like this one https://regex101.com
CodePudding user response:
For the example string, you can add an extra capture group before the opening <
Note that you don't need the /m
flag as there are no anchors in the pattern.
The .*?
part can be written using a negated character class [^,\r\n]*
to match any char except a newline or ,
to prevent the non greedy quantifier and some backtracking.
See a PHP demo and a regex demo.
$pattern = '/(pos=)<([^,\r\n]*),([^,\r\n]*),([^,\r\n]*)>/';
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
print_r($matches);
}
else{
echo "No matches found";
}
Output
Found matches:
Array
(
[0] => Array
(
[0] => pos=<3748.4, 5976.5, 403.3>
)
[1] => Array
(
[0] => pos=
)
[2] => Array
(
[0] => 3748.4
)
[3] => Array
(
[0] => 5976.5
)
[4] => Array
(
[0] => 403.3
)
)