特定单词的php请求,但可以用空格

时间:2017-04-17 19:42:23

标签: php regex

我有一个关于正则表达式的问题,即使用与PHP一起使用的语法。 我知道关于正则表达式的一些基础知识,所以我知道我可以匹配

preg_match("/[maxmustermann ]/u", $input_line, $output_array);

现在我想匹配包含可选的几个单词的所有文本,这些单词可以用空格分隔。

抱歉,我只是不知道该怎么问。我试着举个例子。我有这个文本,想要匹配所有粗体。

  

orem ipsum dolor sit amet,consectetur max adipiscing elit。 Proin maxm pellentesque dui maxmustermann eu erat mustermann rhoncus tempor sit amet quis odio。 Max Mustermann 习惯性morbi tristique senectus et netus et malesuada fames ac turpis egestas。 Max Muster Mann et malesuada fames ac ante ipsum primis in faucibus。 Nam vitae nisl dui。

这意味着我有两个词: max mustermann ,我希望匹配包含 max 和/或 mustermann 按顺序排列,也是随机放置的空间。

谢谢

3 个答案:

答案 0 :(得分:2)

您无法仅使用正则表达式执行此操作。您首先需要提取所选字母组成的所有单词,然后您必须过滤这些单词。像这样:

$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;
});

demo

如果要执行替换,可以采用类似的方式:

$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);

demo

答案 1 :(得分:1)

您希望使用此正则表达式进行不区分大小写的匹配:

/(max)|(muster)|(mann)/i

EXAMPLE

编辑:感谢@AbraCadaver指出你还需要preg_match_all()

答案 2 :(得分:1)

修改更新:

重新阅读问题后,这是一个修改后的答案 只需使用下面的正则表达式执行preg_match_all。

OP标准:

  

我希望匹配包含可选的几个单词的所有文本,这些单词可以分开    一个空间。 ......

     

我希望匹配包含max和/或mustermann字母的单词(一个或多个)    它们的顺序也是随机放置的空间。

为此你需要使用空白边界 所有项子串都由另一个单词边界保持排序。

此正则表达式还将匹配由空格分隔的一组子字符串。

(?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)

101 demo

基准

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