正则表达式检测字符串中的子字符串,并替换为白色 space

Regex detect a sub-string from a string, and replace with white space

需要从字符串中检测“Índice - n -”形式的子字符串的所有实例,并将它们替换为白色 space。

此外,“n”可以是任意正数,字符串前后和单词之间可以有 1 个或多个 space。

我觉得我可以使用这个功能:

$myString = preg_replace( '/\sÍndice\s+/', ' ', $myString );

但是我卡在了正则表达式中。

例如:

"This is a sentence Índice - 8 - forever" 会成为 “This is a sentence forever

"Just do it. Índice - 3 -" 会成为 "Just do it. "

请帮忙。

你可以使用这个正则表达式:

代码:

$arr = [
    "This is a sentence Índice - 8 -    forever",
    "Just do it. Índice - 3 -",
];
foreach ($arr as $str) {
    echo preg_replace('/\h*Índice - \d+ -\h*/', ' ', $str), "\n";
}

输出:

This is a sentence forever
Just do it. 

Demo & explanation