PHP 需要正则表达式专家 - 在字符串中查找带有通配符的文本
PHP Regex expert needed - find text within string but with wildcard
我目前有匹配的代码
$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..."
希望这是可以理解的。它还需要匹配文本在句子中出现的位置,并通过在开始和结束处添加 * 来标记它。
您可以使用 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 = '**';
foreach ($data as $data_) {
$line = preg_replace($pattern, $replacement, $data_, -1, $count)."\n";
if ($count > 0) {
break;
}
}
echo $line;
会 return:
*just because I like that song, does not mean* I will buy it
count
变量将包含根据文档进行的替换次数。我添加它是因为看起来您想在第一次替换后跳出循环。
我目前有匹配的代码
$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..."
希望这是可以理解的。它还需要匹配文本在句子中出现的位置,并通过在开始和结束处添加 * 来标记它。
您可以使用 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 = '**';
foreach ($data as $data_) {
$line = preg_replace($pattern, $replacement, $data_, -1, $count)."\n";
if ($count > 0) {
break;
}
}
echo $line;
会 return:
*just because I like that song, does not mean* I will buy it
count
变量将包含根据文档进行的替换次数。我添加它是因为看起来您想在第一次替换后跳出循环。