我正在尝试用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.
这几乎是我正在寻找的输出。我希望替换只影响单个单词。在这种情况下,它替换了"Johanna"中的"na",从而产生了"Johan"。它仍然应该打印出"约翰娜"。
这可能吗?
编辑:我无法控制$rawstring。这只是一个例子。
要不匹配单词的某些部分,您需要使用 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;
如果您
已经知道字符串并且只是想在某些地方进行子订阅,我会看看 http://php.net/sprintf。 很抱歉我的答案还没有足够的代表发表评论。
我会设置一个关联数组来设置要替换的变量。- 编辑,不得不转义 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.