使用php搜索文本文件

时间:2019-06-08 17:50:22

标签: php regex search text

我正在尝试找到“你好”并获取所有短语/句子,它们位于“ ----”之间

//in my text file 
$txt="
----hello, how are you----
----how are you,hello, how are you----
----how are you hello, how are you----
----hello how are you , how are you----
----how are you , how are you----

"

如果其中有hello个单词,如何获得----之间的所有行?

我的代码

$re = '/(?=.*hello)(----.+?----)/m';
$fh = fopen('ara.txt', 'r') or die($php_errormsg); 
while (!feof($fn)) { 
$line = fgets($fn, 4096);

preg_match_all($re, $line, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);
}

4 个答案:

答案 0 :(得分:1)

尝试使用preg_match_all功能

    //in my text file
    $txt = "
----hello, how are you----
----how are you,hello, how are you----
----how are you hello, how are you----
----hello how are you , how are you----
----how are you , how are you----";

    $pattern = "/[^\\n]*hello[^\\n]*/";
    preg_match_all($pattern,$txt, $matches, PREG_OFFSET_CAPTURE);

    $final = [];
    foreach($matches[0]??[] as $match){
        $final[] = str_replace('----','',$match[0]);
    }
    print_r($final);

答案 1 :(得分:1)

这样更容易

$txt="
----hello, how are you----
----how are you,hello, how are you----
----how are you hello, how are you----
----hello how are you , how are you----
----how are you , how are you----

";

preg_match_all('/\-\-\-\-(.*hello.*)\-\-\-\-/', $txt, $matches);

print_r($matches[1]);

Array ( [0] => hello, how are you [1] => how are you,hello, how are you [2] => how are you hello, how are you [3] => hello how are you , how are you )

答案 2 :(得分:1)

如果我们所有的字符串都有----,我们将简单地使用以下表达式:

(?=.*hello).*

测试

$re = '/(?=.*hello).*/m';
$str = '----hello, how are you----
----how are you,hello, how are you----
----how are you hello, how are you----
----hello how are you , how are you----
----how are you , how are you----
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

Demo 1

如果没有,我们必须验证----,则将表达式扩展为:

(?=.*hello)(----.+?----)

测试

$re = '/(?=.*hello)(----.+?----)/m';
$str = '----hello, how are you----
----how are you,hello, how are you----
----how are you hello, how are you----
----hello how are you , how are you----
----how are you , how are you----
---hello how are you , how are you---
';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

Demo 2

RegEx

如果不需要此表达式,并且希望对其进行修改,请访问regex101.com上的此链接。

RegEx电路

jex.im可视化正则表达式:

enter image description here

我们的代码可能类似于:

$re = '/(?=.*hello)(----.+?----)/m';
$fh = fopen('/path/to/our/file/ara.txt', 'r') or die($php_errormsg);
while (!feof($fh)) {
    $line = fgets($fh, 4096);
    preg_match_all($re, $line, $matches, PREG_SET_ORDER, 0);
    var_dump($matches);
}

答案 3 :(得分:1)

如果接下来的事情是你好,则不需要肯定的前行(?=.*hello来断言。

您可以使用具有非贪婪匹配.*?的捕获组来防止过度匹配,并将hello置于单词边界\b之间:

----(.*?\bhello\b.*?)----

查看regex demo

您的值将在第一个捕获组中。