我有一个关于regex的问题,即使用php的语法。我了解php中regex的一些基本知识,所以我知道我可以用
preg_match("/[maxmustermann ]/u", $input_line, $output_array);现在,我想匹配所有的文本,其中包含可选的几个单词,这些词可以用空格分隔。
对不起,我只是不知道该怎么问。我试着做个例子。我有这篇文章,并想要匹配所有的大胆的。
同坐,圣洁max绝热精灵。Proin maxm pellentesque dui maxmustermann eu erat mustermann rhoncus,或坐姿相同。Max Mustermann居住者morbi tristique et netus et malesuada fames ac turpis egestas。Max召集Mann, et malesuada,著名的在羊草中的前原核。nisl dui。
这意味着我有两个单词:max,和mustermann,我想匹配单词(多一个),其中包含max和/或mustermann的字母,它们是如何排列的,也是随机放置的空间。
谢谢
发布于 2017-04-17 20:04:37
你不能只用regex这样做。您首先需要提取所有由您选定的字母组成的单词,而在第二次您必须过滤这些单词。就像这样:
$word = 'maxmustermann';
preg_match_all('~\b[aemnrstux]+\b~ui', $txt, $matches);
$result = array_filter($matches[0], function ($i) use ($word) {
return stripos($word, $i) !== false;
});如果要执行替换操作,可以采用类似的方式:
$word = 'maxmustermann';
$result = preg_replace_callback('~\b[aemnrstux]+\b~ui', function ($m) use ($word) {
return stripos($word, $m[0]) !== false ? "#{$m[0]}#" : $m[0];
}, $txt);发布于 2017-04-17 20:51:01
编辑更新:
在重读问题后,这是一个修正的答案.
只需使用下面的正则表达式执行preg_match_all即可。
执行部分标准:
我想匹配所有的文本,其中包含可选的几个词,可以通过一个空格分隔。..。 我想匹配单词(多一个),其中包含的字母max和/或mustermann的顺序,他们是如何,但也随机放置的空间。
为此,您需要使用空白边界。
所有的项子串都由一个可选的单词边界来排序。
此regex还将匹配一组由空格分隔的子字符串。
(?i)(?<!\S)(?!\s)(?:m|\b)(?:a|\b)(?:x|\b)(?:m|\b)(?:u|\b)(?:s|\b)(?:t|\b)(?:e|\b)(?:r|\b)(?:m|\b)(?:a|\b)(?:n|\b)(?:n|\b)(?:\s+(?!\s)(?:m|\b)(?:a|\b)(?:x|\b)(?:m|\b)(?:u|\b)(?:s|\b)(?:t|\b)(?:e|\b)(?:r|\b)(?:m|\b)(?:a|\b)(?:n|\b)(?:n|\b))*(?!\S)
基准测试
Regex1: (?i)(?<!\S)(?!\s)(?:m|\b)(?:a|\b)(?:x|\b)(?:m|\b)(?:u|\b)(?:s|\b)(?:t|\b)(?:e|\b)(?:r|\b)(?:m|\b)(?:a|\b)(?:n|\b)(?:n|\b)(?:\s+(?!\s)(?:m|\b)(?:a|\b)(?:x|\b)(?:m|\b)(?:u|\b)(?:s|\b)(?:t|\b)(?:e|\b)(?:r|\b)(?:m|\b)(?:a|\b)(?:n|\b)(?:n|\b))*(?!\S)
Completed iterations: 50 / 50 ( x 1000 )
Matches found per iteration: 6
Elapsed Time: 10.42 s, 10421.84 ms, 10421843 µs解说
(?i) # Case insensitive modifier
(?<! \S ) # Whitespace boundary behind
(?! \s ) # Insure one of the next substrings match
(?: m | \b )
(?: a | \b )
(?: x | \b )
(?: m | \b )
(?: u | \b )
(?: s | \b )
(?: t | \b )
(?: e | \b )
(?: r | \b )
(?: m | \b )
(?: a | \b )
(?: n | \b )
(?: n | \b )
(?:
\s+ # Optional space and more words
(?! \s ) # Insure one of the next substrings match
(?: m | \b )
(?: a | \b )
(?: x | \b )
(?: m | \b )
(?: u | \b )
(?: s | \b )
(?: t | \b )
(?: e | \b )
(?: r | \b )
(?: m | \b )
(?: a | \b )
(?: n | \b )
(?: n | \b )
)*
(?! \S ) # Whitespace boundary ahead发布于 2017-04-17 19:47:28
https://stackoverflow.com/questions/43458438
复制相似问题