模式匹配前后特定长度的preg_match_all

时间:2018-10-26 08:19:02

标签: php regex pattern-matching

我有一个代码,可以从大字符串的一部分中找到与模式匹配的整行。

$searchfor = 'some unicode words';

$pattern = preg_quote($searchfor, '/');

$pattern = "/^.*$pattern.*\$/m";

if(preg_match_all($pattern, $chunk, $matches)){

    echo "Found matches:\n";

    echo implode("\n", $matches[0]);

}

但是,我不希望与搜索词匹配的整行。我需要在针头前后加上10个字符的单词。请参阅以下示例以更好地理解。

源句:

这是我一生中见过的非常大的文字行,我很喜欢。

针:

我有

输出:

我见过的文字行

(针头前后有10个字符)

如何更改将支持上述条件的模式。

TIA。

1 个答案:

答案 0 :(得分:0)

您可以通过在搜索字符串的两侧查找10个字符并将它们与搜索字符串分组来修改模式:

/^.*?(.{1,10}$pattern.{1,10}).*$/

请注意,我们使用{1,10}而不是{10},因为如果在源的开头或结尾附近找到了搜索字符串,则可能没有10个字符可用于填充匹配项。以下是一些示例:

$chunk = 'This is a very large text line I have ever seen in my life and I love it.';
$searchfor = 'I have';
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*?(.{1,10}$pattern.{1,10}).*$/m";
if(preg_match_all($pattern, $chunk, $matches)){
    echo "Found matches:\n";
    echo implode("\n", $matches[1]) . "\n";
}
$searchfor = 'a very';
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*?(.{1,10}$pattern.{1,10}).*$/m";
if(preg_match_all($pattern, $chunk, $matches)){
    echo "Found matches:\n";
    echo implode("\n", $matches[1]) . "\n";
}
$searchfor = 'and I';
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*?(.{1,10}$pattern.{1,10}).*$/m";
if(preg_match_all($pattern, $chunk, $matches)){
    echo "Found matches:\n";
    echo implode("\n", $matches[1]) . "\n";
}

输出

Found matches:
text line I have ever seen 
Found matches: 
This is a very large tex 
Found matches: 
n my life and I love it.

Demo on 3v4l.org