PHP搜索和回显特定文本 [英] PHP search and echo specific text
问题描述
我遇到了问题。我想做的是让我的PHP代码进行搜索,直到找到所输入的内容。例如,如果我搜索数字 12。我希望它进入下面的文件,并找到其中包含 12的行。
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,
在这种情况下,该行中将包含12个:
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!
推荐答案
尝试下面的代码
$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
就像
if($matches[1] == 'Dark Green')
{
echo $matches[1];
}
或
if($matches[2] == 11)
{
echo $matches[2];
}
(...)
获取文件中的文本尝试使用
(...) To get the text in the file try use
$string = file_get_contents('file.txt');
这篇关于PHP搜索和回显特定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!