【问题标题】:PHP Regex expert needed - find text within string but with wildcard需要 PHP 正则表达式专家 - 在字符串中查找文本但使用通配符
【发布时间】:2017-08-12 17:04:57
【问题描述】:

我目前有匹配的代码

$data=["as much as I like oranges, I like bananas better",
"there's no rest for the wicked",
"the further I move from my target, the further I get",
"just because I like that song, does not mean I will buy it"];

 if (stripos($data[1], 'just because I') !== false) {
      $line=str_ireplace('just because I','*'.just because I.'*',$data[1]);
      break;
  }

这种方式只匹配包含该文本的任何句子。但我想要它做的是匹配一个通配符,这样它就可以检测一个句型。例如,它可以检测到:

"just because I... (<<any text in between>>) ...does not mean..."

希望这是可以理解的。它还需要匹配文本在句子中出现的位置,并通过在开头和结尾添加 * 来标记它。

【问题讨论】:

    标签: php regex preg-match wildcard strpos


    【解决方案1】:

    您可以使用preg_replace 代替str_ireplace

    $data = ["as much as I like oranges, I like bananas better",
             "there's no rest for the wicked",
             "the further I move from my target, the further I get",
             "just because I like that song, does not mean I will buy it",
             "the further I move from my target, the further I get"];
    $pattern = '/(.*)(just because I .* does not mean)(.*)/i';
    $replacement = '$1*$2*$3';
    foreach ($data as $data_) {
      $line = preg_replace($pattern, $replacement, $data_, -1, $count)."\n";
      if ($count > 0) {
        break;
      }
    }
    echo $line;
    

    将返回:

    *just because I like that song, does not mean* I will buy it
    

    count 变量将包含按照文档进行的替换次数。我添加它是因为看起来你想在第一次替换后跳出循环。

    【讨论】:

    • 绝对完美。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2011-06-11
    相关资源
    最近更新 更多