问题描述
需要从字符串中检测形式为“ Índice - n -
”的子字符串的所有实例,并将其替换为空格。
此外,“ n”可以是任何正数,并且在字符串前后,单词之间可以有1个或多个空格。
我想我可以使用此功能:
$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.