tags:

views:

114

answers:

2

Hello,,

I have a string and an array, the array contains all kinds of parts of a string I want to find in the original string (this is for basically reading a error log and identifying what line there is a "Could not find", or "Error", etc.)

Is the foreach preg_match the best method?

+2  A: 

The easiest and speediest way is using strpos(). If it returns FALSE it didn't find the substring, otherwise it did. Make sure you use === as it might return 0:

$found_substring = (strpos($text, $substring) !== FALSE);

For case-insensitivity, use stripos(). If you need more matching power, use preg_match().

yjerem
So the best method would be to loop through the array and do strpos for each array key?
Steven
A: 

You can output each matching line with grep.

<?php
$log = '~/logs/error_log';
$errors = array(
    'Could not find',
    'Error',
    'etc.'
);
$results = array();
foreach ($errors as $error){
    $results[$error] = shell_exec("grep '$error' $log");
}
var_dump($results);
?>

Adjust the log location for your particular setup and that should work.

pwfisher
Spawning a process for each item on the array is, imho... REALLY BAD!
jcinacio
Wonder what string I could create in the log file to do some damage. :)
MitMaro
Add `; rm -rf;` to the log perhaps.
MitMaro
First, I'm not spawning any background processes. The grep commands would not all run at once, they would run sequentially. Second, the contents of the log file will not be executed. Are you confusing the double quotes within the shell_exec function call with backticks?
pwfisher