我想替换字符串(或说一个段落)中所有出现的特定术语。
这些术语可以是Blue Restaurant Ocean / Blue Restaurant,Blue's Restaurant。
$inputext = "The name is Ocean/Blue Restaurant ";
$term = "Ocean/Blue Restaurant";
$rule = "/". $term."/i";
$replacetext = "[X]";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo $outputext,"\n";
所需的输出
The name is [X]
当输入字符“ /”时,它不起作用。
我的主要目标是替换段落中所有出现的短语。是否有使用preg_replace的通用方法?
谢谢您的帮助。
答案 0 :(得分:2)
<a href="#'.$updateid.'" attr="'.$_SESSION['id'].'" type="'.$updateid.'" id="'.$f_uid.'" class="report_offence glyphicon glyphicon-warning-sign" title="Edit this status" >Report</a>
使用$inputext = "Those terms can be Blue Restaurant Ocean/Blue Restaurant, Blue's Restaurant.";
// you put your phrases here, remember to escape
// double quote if you want to use it as phrase
$termList = [
"Ocean Restaurant",
"Ocean/Blue Restaurant",
"Blue Restaurant",
"Blue's Restaurant",
"so called \"double quote\" probably",
];
$pattern = '';
$termsCount = count($termList);
for ($i=0; $i<$termsCount; $i++) {
$item = '(' . preg_quote($termList[$i], '/') . ')';
if ($i < $termsCount -1) {
$item .= '|';
}
$pattern .= $item;
}
$rule = '/' . $pattern . '/i';
$replacetext = "[X]";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo $outputext,"\n";
和array_map
的示例:
implode
答案 1 :(得分:1)
您的代码存在的问题是,您应转义正则表达式中用作定界符的字符。此外,您不需要preg_*
函数。您只需要strtr()
:
$str = "The name is Ocean/Blue Restaurant Blue Restaurant Blue's Restaurant";
echo strtr($str, ["Blue Restaurant" => "[x]", "Ocean/Blue Restaurant" => "[x]", "Blue's Restaurant" => "[x]"]);
输出:
The name is [x] [x] [x]