php - 正则表达式 - 如果 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
/^。$模式。\$/我
解决方案
这个表情,
(?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可视化正则表达式:
推荐阅读
- android - 如何从 firebase 获取多个密钥
- ruby-on-rails - 如何在 ruby on rails 中将日期格式从 dd-mmm-yyyy 转换为 yyyy-mm-dd
- java - 如何在多线程线程中传递上下文
- algorithm - 从给定的字符串生成一组唯一的数字/字符串
- python - 如何将 df 中的列转换为具有日期时间格式的纪元,反之亦然?
- javascript - Service Worker 在本地工作,但在托管我的网站后未注册
- sql - SQL 查询需要时间执行
- javascript - 从 json 获取图像位置
- elixir - Elixir 应用程序中的多个主管
- kubernetes - tcp 10.0.2.15:6443:getsockopt:Debian 9 VM 上的连接被拒绝