首页 > 解决方案 > 正则表达式 - 如果 PHP preg_match_all 有特定的单词和不区分大小写,则匹配整行

问题描述

我有一个简单的正则表达式代码来匹配具有特定单词的文本文件中的整行。我使用 PHP 函数 preg_match_all。

这是我的正则表达式模式:

$word= 'world';
$contents = '
this is my WoRld
this is my world
this is my wORLD
this is my home
';
$pattern = "/^.*$word.*\$/m";
preg_match_all($pattern, $contents, $matches);

// results will be in $matches[0]

此函数获取整行但仅搜索区分大小写,因此它将仅返回文本的第二行。

我希望它匹配所有行(任何形式的“世界”字)。

我阅读了有关使用 /i 的信息,但我不知道如何将它与上面的模式结合起来。

我试过了:

/^。$模式。\$/m/i

/^。$模式。\$/m/i

/^。$模式。\$/我

标签: phpregexpreg-match-all

解决方案


这个表情,

(?i)^.*\bworld\b.*$

可能只是返回那些所需的字符串。

测试

$re = '/(?i)^.*\bworld\b.*$/m';
$str = 'this is my WoRld
this is my world
this is my wORLD
this is my home';

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

var_dump($matches);

输出

array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(16) "this is my WoRld"
  }
  [1]=>
  array(1) {
    [0]=>
    string(16) "this is my world"
  }
  [2]=>
  array(1) {
    [0]=>
    string(16) "this is my wORLD"
  }
}

正则表达式电路

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

在此处输入图像描述


推荐阅读