$text = text1 text2 text3 text4
if (preg_match('/text1/',$text ))
$replacetext1= 'replacetext1';
else
$replacetext1='';
if (preg_match('/text2/',$text ))
$replacetext2= 'replacetext2';
else
$replacetext2='';
if (preg_match('/text3/',$text ))
$replacetext3= 'replacetext3';
else
$replacetext3='';
if (preg_match('/text4/',$text ))
$replacetext4= 'replacetext4';
else
$replacetext4='';
result = replacetext1 replacetext2 replacetext3 replacetext4
我想处理输入及其自动替换
text1 | replacetext1
text2 | replacetext2
text3 | replacetext3
text4 | replacetext4
FORMAT: KEYWORD|RESONSE-1|
有什么简单的方法可以替换单词??
答案 0 :(得分:0)
您可以使用str_replace
的数组支持:
$text = "text1 text2 text3";
$result = str_replace(["text1","text2","text3"], ["repl1", "repl2", "repl3"], $text);
答案 1 :(得分:0)
类似这样的东西:
$text = "text4 text1 text2 text3";
$replace = [
'/\btext1\b/' => 'replace1', //replace case sensitive
'/\btext2\b/i' => 'replace2', //non-sensitive
'/\b(text3|text4)\b/i' => 'replace3', //replace both text3 and text4
];
$result = preg_replace(array_keys($replace), $replace, $text);
这里最主要的是\b
或单词边界,这是不是0-9a-zA-Z_
的东西,它可以防止部分匹配。但是从理论上讲,您可以对数组中的任何项目使用任何正则表达式。与其他替换方法相比,它具有更大的灵活性。
输出:
replace3 replace1 replace2 replace3
答案 2 :(得分:0)
一种方法是使用像这样的爆破/爆炸方法:
$text = "text1 text2 text3 text4";
// define your replacement strings
$replace = [
'text1' => 'replace1',
'text2' => 'replace2',
'text3' => 'replace3',
'text4' => 'replace4',
];
$result = $text;
foreach($replace as $i => $v){
$result = implode($v, explode($i, $result ));
}
echo $result ;