PHP search and echo specific text

2019-01-29 13:45发布

问题:

I'm having a problem. What I want to do is make my PHP code do a search until it finds what was entered. For example if I searched the number "12." I want it to go in a file like the one below and find the line that has "12" in it.

Dark Green = 11 = No = 20,
Light Blue = 12 = No = 20,
Lime Green = 13 = No = 20,
Sensei Gray = 14 = Yes = 0,

In that case this line would have the 12 in it:

Light Blue = 12 = No = 20,

Next what I want the code to do after it finds the line is for it to read the text that is before the "=" sign to the left of it. In this case I would want my code to read:

Light Blue

I've always wanted to do this and any help would be HIGHLY appreciated!

回答1:

Try the code below

$string = 'Dark Green = 11 = No = 20,
Light Blue = 12 = No = 20,
Lime Green = 13 = No = 20,
Sensei Gray = 14 = Yes = 0';


$string = explode(',',$string);
foreach($string as $row)
{
    preg_match('/^(\D+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/', trim($row), $matches);
    echo $matches[1];//Dark Green
    echo $matches[2];//11
    echo $matches[3];//No
    echo $matches[4];//20
}

In the loop use to check the word to search

Like that

if($matches[1] == 'Dark Green')
{
   echo $matches[1];
}

or

   if($matches[2] == 11)
    {
       echo $matches[2];
    }

(...) To get the text in the file try use

    $string = file_get_contents('file.txt');


回答2:

In broad terms, you can use php fgets command to process any text file line by line. Then, you can run an operation on each line, using explode as suggested above to find your string and print it.



回答3:

Try something like this

$lines = explode("\n",$filetext);
$searchString = preg_quote('12','/');
foreach($lines as $line) {
    preg_match("/([^=])\s*=\s*$searchString/");
    if($matches[1]) {
         print $matches[1]; 
         break;
    }
}

where $filetext has the text in it either using fgets to read line by line (then you don't need explode) or even simpler using file_get_contents



回答4:

Here is a mixture of preg_grep and explode.

$arr = explode("\n", file_get_contents('file.txt'));
$matches = preg_grep('/12/', $arr);

Your matches would be in the $matches array;



回答5:

use this:

$data = file("file.txt");
$num = 12;
foreach((array)$data as $key=>$line) {
   if (strstr($line,"= $num ") || strstr($line," = $num,")) {
      echo $line;
      break;
   }
}