简体   繁体   中英

How to check if string has specific letters?

I have a text file that contains many lines of random English letters. I want to check which lines contain the letters that I'm looking for. For example, I have the following text lines:

pwieuthvngbcdxz
iaefonmlkjghbcd
plmujhytrgvdsea

and I want to know if any line contains the following letters: abcdefghijklmno , not in any order, so the result would be line #2: iaefonmlkjghbcd

So far I only have the part that reads the text file lines:

$handle = fopen("randomletters.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        //does $line contain the letters I'm looking for? if yes print the line
    }
}   

You could use the strpos function. It returns the index of a string in another string or FALSE if not found.

$handle = fopen("randomletters.txt", "r");
$chars = str_split('abcdefghijklmno');
if ($handle) {
    while (($line = fgets($handle)) !== false) {
       $contain = true;
       foreach ($chars as $char) {
           if(strpos($line, $char) === false){
                $contain = false;
                break
           }
       }
       if($contain) {
           return $line
       }
    }
}   

Here, i've also used the str_split function and check for each line, for each char, if it exists. If not, we go to the other line. If it does, we returns the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM