需要PHP Regex专家 - 在字符串中查找文本但使用通配符

时间:2022-09-27 19:28:13

I have code currently that matches

我目前的代码匹配

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

This way simply matches any sentence that contains that text. But what I want it to do is match with a wild card so it can detect a sentence pattern. So for example it can detect:

这种方式只匹配包含该文本的任何句子。但我想要它做的是匹配外卡,以便它可以检测句子模式。例如,它可以检测到:

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

Hope this is understandable. It also needs to match where the text occurs in the sentence and mark it by adding * to the start and end.

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

1 个解决方案

#1


1  

You can use preg_replace instead of str_ireplace:

您可以使用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;

Will return:

将返回:

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

The count variable will contain the number of replacements made, as per the documentation. I added it because it looks like you want to break out of the loop after the first replacement is made.

count变量将包含根据文档所做的替换次数。我添加了它,因为看起来你想要在第一次替换之后突破循环。

#1


1  

You can use preg_replace instead of str_ireplace:

您可以使用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;

Will return:

将返回:

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

The count variable will contain the number of replacements made, as per the documentation. I added it because it looks like you want to break out of the loop after the first replacement is made.

count变量将包含根据文档所做的替换次数。我添加了它,因为看起来你想要在第一次替换之后突破循环。