Php 理解下面的正则表达式
我写了一个正则表达式,但它并不像我期望的那样工作。请看一看Php 理解下面的正则表达式,php,regex,Php,Regex,我写了一个正则表达式,但它并不像我期望的那样工作。请看一看 [^\s]*”.preg_quote($word)。“[^\s]/ 如果包含关键字,则此部分匹配整个单词,例如,如果搜索wor关键字,则匹配关键字 {0,65}?[^\s]*”.preg_quote($word)。“[^\s]*。{0,65} 在这里,我得到了多达65个字符之前和之后的关键字,即,我会得到 这里有很多单词关键字和其他单词 现在,问题是什么。如果{65}个字符中有[.:]个字符,我会尝试从开头匹配这个句子 如果我有sa
[^\s]*”.preg_quote($word)。“[^\s]
/
如果包含关键字,则此部分匹配整个单词,例如,如果搜索wor关键字,则匹配关键字
{0,65}?[^\s]*”.preg_quote($word)。“[^\s]*。{0,65}
在这里,我得到了多达65个字符之前和之后的关键字,即,我会得到
这里有很多单词关键字和其他单词
现在,问题是什么。如果{65}个字符中有[.:]个字符,我会尝试从开头匹配这个句子 如果我有sach结构-word1 word2{这里少于65个字符}关键字{这里的其他字符} 我想,如果我写了
([\.\:]?)(.{0,65}?[^\s]*”.preg\u quote($word)。“[^\s]*。{0,65})
它将匹配{此处少于65个字符}关键字{65个字符}
但事实并非如此。部分[\.\:]?
对正则表达式没有任何影响。它匹配所有{65}个字符
我需要从头开始匹配句子,如果关键字前面65个字符以内的句子开头只需替换拳头即可
.{0,65}
借
毕竟,它可能看起来像
preg_match_all("/([^\.\:]{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65})/siu",$content,$matched);
[.:]?
的意思是“匹配一个点(
)、一个冒号(:
),或者什么都不匹配”;如果下一个字符不是点或冒号,([.:]?)
不匹配任何内容。然后,{0,65}
匹配最多65项,包括
或:
。我想这就是你想要的:
$source='A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids.';
$word = 'regular';
preg_match_all('#[^.:]{0,65}\b'.preg_quote($word).'\b.{0,65}#siu', $source, $matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => A regular expression (regex or regexp for short) is a special text string
[1] => You can think of regular expressions as wildcards on steroids.
)
)
(现场直播)
$source='A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids.';
$word = 'regular';
preg_match_all('#[^.:]{0,65}\b'.preg_quote($word).'\b.{0,65}#siu', $source, $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => A regular expression (regex or regexp for short) is a special text string
[1] => You can think of regular expressions as wildcards on steroids.
)
)