是否有一个PHP函数来匹配文件上的3个连续行

时间:2017-06-13 03:59:11

标签: php bash scripting

任何可以提供建议的人,我正在寻找一个PHP函数或方法来匹配文件上的3个连续行,例如

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

我如何匹配以上文字中的以下内容?

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

目前我可以匹配一条线。

1 个答案:

答案 0 :(得分:0)

可以通过三种方式实现。

首先使用regexpreg_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";

如果您只是需要知道是否存在任何单词,请使用上述preg_match。如果您需要匹配任何字词的所有出现,请使用preg_match_all|管道符号表示or

其次使用stripos()表示字符串是否包含特定单词,如果包含,则返回单词的起始位置。

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

Thridly 如果您使用,分隔符分隔字符串句子,则可以使用explode()将字符串转换为数组然后与另一个数组逐个匹配。

$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>";
        }
    }
}