用一个字符串替换多个字符串

时间:2015-03-09 19:33:23

标签: 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. 
$substitution = array('');

$greeting = str_ireplace($placeholders, $substitution, $rawstring);

echo  $greeting . "<br />";
?>

这是结果字符串:

Hello . Your is a pleasure to have! Your friend Johan is also here.

这几乎是我正在寻找的输出。 我希望替换只影响单个单词。在这种情况下,它取代了&#39; na&#39;在&#39;约翰娜&#39;,导致约翰&#39;。它仍然应该打印出约翰娜&#39;

这可能吗?

编辑:我无法控制$ rawstring。这只是一个例子。

3 个答案:

答案 0 :(得分:2)

要匹配单词的某些部分,您需要使用preg_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;

答案 1 :(得分:0)

我设置了一个关联数组来设置替换的变量。 - 编辑,不得不逃避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.

答案 2 :(得分:0)

如果您已经知道该字符串,我会查看http://php.net/sprintf,并且只是想在某些地方进行分析。对不起,答案我还没有足够的代表发表评论。