Php 用一个字符串替换多个字符串
我试图用PHP中的一个字符串替换几个可能的字符串。此外,字符串必须只匹配一个完整的单词:Php 用一个字符串替换多个字符串,php,Php,我试图用PHP中的一个字符串替换几个可能的字符串。此外,字符串必须只匹配一个完整的单词: <? $rawstring = "Hello NONE. Your N/A is a pleasure to have! Your friend Johanna is also here."; //strings for substitution $placeholders = array('N/A', 'NA', 'NONE'); //replace with blank spaces. $
<?
$rawstring = "Hello NONE. Your N/A is a pleasure to have! Your friend Johanna is also here.";
//strings for substitution
$placeholders = array('N/A', 'NA', 'NONE');
//replace with blank spaces.
$substitution = array('');
$greeting = str_ireplace($placeholders, $substitution, $rawstring);
echo $greeting . "<br />";
?>
这几乎就是我想要的输出。
我希望替换只影响单个单词。在本例中,它将替换“Johanna”中的“na”,从而生成“Johan”。它仍然应该打印出“Johanna”
这可能吗
编辑:我无法控制$rawstring。这只是一个例子。我设置了一个关联数组来设置替换变量。 -编辑,必须在N/A中转义斜杠
$val_to_swap_in = '';
$replacers = array(
'/NONE/' => $val_to_swap_in,
'/N\/A/' => $val_to_swap_in,
'/NA/' => $val_to_swap_in,
);
$greeting = preg_replace(array_keys($replacers), array_values($replacers), $rawstring);
在php cli shell中导致此问题:
Hello . Your is a pleasure to have! Your friend Johanna is also here.
我想看看你是否已经知道了弦,并且只是想在某些点上下潜。很抱歉,我没有足够的代表发表评论。若要与单词的某些部分不匹配,您需要使用
preg\u replace()
试着这样做:
$rawstring = "Hello NONE. Your N/A is a pleasure to have! Your friend Johanna is also here.";
$placeholders = array('N/A', 'NA', 'NONE');
//Turn $placeholders into an array of regular expressions
// `#` delimits the regular expression. Make sure this doesn't appear in $placeholders.
// `(.+)` matches and captures any string of characters
// `\b` matches word boundaries
// `${1}` reinserts the captured pattern.
// `i` at the end makes this case insensitive.
$re = preg_replace('#(.+)#', '#\b${1}\b#i', $placeholders);
//Make the same substitution for all matches.
$substitution = '';
$greeting = preg_replace($re, $substitution, $rawstring);
echo $greeting;
不幸的是,我无法控制传入的字符串。我无法替换令牌。将替换为字符串(
$substitution='';
)将为您进行替换。更棘手的部分只是替换“整词”。为此,常用的方法是使用a和,如$result=preg_replace('/\bSQUIRREL\b/i',kitty',噢,看,一只松鼠!')我喜欢你在那里所做的一切。非常简洁的替换机制,也感谢解释$re变量的注释。
$rawstring = "Hello NONE. Your N/A is a pleasure to have! Your friend Johanna is also here.";
$placeholders = array('N/A', 'NA', 'NONE');
//Turn $placeholders into an array of regular expressions
// `#` delimits the regular expression. Make sure this doesn't appear in $placeholders.
// `(.+)` matches and captures any string of characters
// `\b` matches word boundaries
// `${1}` reinserts the captured pattern.
// `i` at the end makes this case insensitive.
$re = preg_replace('#(.+)#', '#\b${1}\b#i', $placeholders);
//Make the same substitution for all matches.
$substitution = '';
$greeting = preg_replace($re, $substitution, $rawstring);
echo $greeting;