Reputation: 323
I am working on a PHP code that reads data from text files and it searches for a certain word and echos it, for example, I search for
[Error]
Is it possible to only echo the word I search for only 1 time (aka if the word "Error" is found twice, only echo it once!)
$file = 'filesexample/'.$fileNameNew;
$searchfor = 'error';
header('Content-Type: text/plain');
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Errors Found:\n";
echo implode("\n", $matches[0]);
}
Can I do this?
Upvotes: 0
Views: 140
Reputation: 6703
You can use the array_unique() PHP's function which remove duplicate values from an array:
if(preg_match_all($pattern, $contents, $matches))
{
$matches[0] = array_unique($matches[0]);
echo "Errors Found:\n";
echo implode("\n", $matches[0]);
}
Upvotes: 2