【问题标题】:Php case insensitive word replacement from a sentence一个句子中的 PHP 不区分大小写的单词替换
【发布时间】:2015-04-18 20:55:30
【问题描述】:

我需要替换句子中的匹配词。我正在使用以下内容,但它区分大小写。我需要不区分大小写。

$originalString  = 'This is test.';
$findString = "is";
$replaceWith = "__";

$replacedString = (str_ireplace($findString, $replaceWith, $originalString));
// output : Th__ __ test.

那我试过了

$replacedString = preg_replace('/\b('.preg_quote($findString).')\b/', $replaceWith, $originalString);
// output : This __ test.

它按预期工作正常,但如果我使用$findString = "Is""iS""IS" 则它不起作用。 任何人都可以建议我什么是正则表达式。获得不区分大小写的替换或任何其他方式来实现所需的结果。

更新

根据@nu11p01n73R 的回答,我在下面进行了更改,但在下面的示例中它会下降。

$originalString  = 'Her (III.1) was the age of 2 years and 11 months. (shoulder a 4/5)';
$findStringArray = array("age", "(III.1)", "2", "months", "4");
foreach($findStringArray as $key => $value) {
    $originalString = preg_replace('/\b('.preg_quote($value).')\b/i', "__", $originalString);
}
//Output : Her (III.1) was the __ of __ years and 11 __. (shoulder a __/5)

//Output should be : Her __ was the __ of __ years and 11 __. (shoulder a 4/5)

如果我在$findStringArray 上添加4/5,它也会停止工作

【问题讨论】:

  • 看起来你只是想替换整个单词(即在空格“ " 上爆炸的字符串),而不是单词中的子集,这是正确的吗?
  • 其实我需要高亮文本
  • 好的,问题是,无论您需要做什么,是否只针对整个“单词”?因为在您的示例中您想突出显示“4”,如果您想在文本中的任何位置突出显示它,@nu11p01n73R 的答案是例外,如果只有“单词”,则需要稍微修改的版本......
  • 不,我不想突出显示4,因为在字符串中它不是4,而是4/5
  • 投反对票的人为什么要投反对票??

标签: php regex replace preg-replace


【解决方案1】:

你需要做的就是在正则表达式的末尾添加一个ignore case modifier i

$originalString  = 'This Is test.';
$findString = "is";
$replaceWith = "__";
$replacedString = preg_replace('/\b('.preg_quote($findString).')\b/i', $replaceWith, $originalString);
// output : This __ test.

【讨论】:

  • @TapasPal 不客气,兄弟 :) 如果您觉得有用,请接受答案;)
  • @TapasPal 遗漏了一些非常小的东西。 1.\b\(III.1\)\b\(\bIII.1\b\)不同。后者只会匹配III.1 2。\b 包含, . / ( ) 等,所以当4/5 中的4 将与\b4\b 匹配。
  • 那么需要改变什么?
【解决方案2】:

(III.1)4/5 不能使用字边界,试试看:

$originalString  = 'Her (III.1) was the age of 2 years and 11 months. (shoulder a 4/5)';
$findStringArray = array("age", "(III.1)", "2", "months", "4/5");
foreach($findStringArray as $key => $value) {
    $originalString = preg_replace('~(?<=^|[. (])'.preg_quote($value).'(?=[. )]|$)~i', "__", $originalString);
    //                            __^       __^                            __^  __^
}
echo $originalString,"\n";

编辑:我已将分隔符从/ 更改为~,并在环视中添加了括号。

输出:

Her __ was the __ of __ years and 11 __. (shoulder a __)

【讨论】:

  • 对不起兄弟,如果我在$findStringArray 上添加4/5,它仍然停止工作
  • @TapasPal:4/5 想要的结果是什么?
  • 输出应该是Her __ was the __ of __ years and 11 __. (shoulder a __)
猜你喜欢
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 2019-07-23
  • 1970-01-01
  • 2010-10-29
  • 2017-02-24
相关资源
最近更新 更多