0

Anyone who can give advise, i'm looking for a php function or method to matching 3 consecutive lines on a file e.g

php is fun,
linux is interesting,
Windows is fun,
Ubuntu is ubuntu,
Perl is fun,

How can i match the below from the above text ?

linux is interesting,
Windows is fun,
Ubuntu is ubuntu,

At the moment i can match if its a single line .

Mike
  • 23,542
  • 14
  • 76
  • 87
sawe
  • 11
  • 6
  • Do you want to make sure that the below text exists in the string give above? – Syed Aqeel Jun 13 '17 at 04:06
  • `file()` to put the values in to an array, then `explode()` your search string on comma, then loop your search array to find matches –  Jun 13 '17 at 04:09
  • "linux is interesting, Windows is fun, Ubuntu is ubuntu," is of course three lines. But, it is single string. Isn't it? Just use string compare function. – Bhavik Shah Jun 13 '17 at 04:11
  • Possible duplicate of [How do I check if a string contains a specific word in PHP?](https://stackoverflow.com/questions/4366730/how-do-i-check-if-a-string-contains-a-specific-word-in-php) – Mike Jun 13 '17 at 04:15

1 Answers1

0

It can be possible in three ways.

Firstly by using regex with preg_match_all()

$str = "php is fun, linux is interesting, Windows is fun, Ubuntu is ubuntu, Perl is fun,";
$res = preg_match_all("/(linux is interesting|Windows is fun|Ubuntu is ubuntu)/", $str);
if ($res)
    echo "Text is founded in string";

If you just need to know if any of the words is present, use preg_match as above. If you need to match all the occurences of any of the words, use preg_match_all and | pipe sign indicates or

secondly by using the stripos() which indicates if a string contains specific words or not and if contains it returns the starting position of the words.

print_r(stripos($str, "Windows is fun"))

Thridly if you are separating your string sentences with , delimiter then it can be possible by using explode() to convert string into array then match one by one with another array.

$str = "php is fun, linux is interesting, Windows is fun, Ubuntu is ubuntu, Perl is fun,";
$exp = explode(",", $str);

$match = array("linux is interesting", "Windows is fun", "Ubuntu is ubuntu");

foreach ($exp as $key => $value) {
    foreach ($match as $key_match => $value_match) {
        if ($value === $value_match) {
            echo "String match founded <br>";
        }
    }
}
Syed Aqeel
  • 1,009
  • 2
  • 13
  • 36
  • thank you , the first method will work perfectly as i want to match the 3 exact 3 lines. – sawe Jun 13 '17 at 05:26