php str_replace和\ b字边界

时间:2010-06-08 04:51:14

标签: php

我正在尝试使用str_replace,但无法弄清楚如何使用\ b作为字边界:

<?php

$str = "East Northeast winds 20 knots";

$search = array("North", "North Northeast", "Northeast", "East Northeast", "East", "East Southeast", "SouthEast", "South Southeast", "South", "South Southwest", "Southwest", "West Southwest", "West", "West Northwest", "Northwest", "North Northwest");

$replace = array("N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW");

$abbr = str_replace($search, $replace, $str);

echo $abbr;


// this example echoes  "E Neast winds 20 knots"   since \b word boundary is not used
//  how to apply word boundary so that is seeks the exact words to replace?
// the text to replace could be anywhere (start, middle, end) of string
// this example should output "ENE winds 20 knots"

?>

2 个答案:

答案 0 :(得分:2)

您不能将\ b与str_replace()一起使用。单词边界“\ b”只是正则表达式中的有效锚点。所以使用preg_replace(),如果您的搜索文本包含自然语言,则更合适:

 $replace = array_combine($search, $replace);
 preg_replace('#\b('.implode('|',$search).')\b#e', '$replace["$1"]?:"$1"', $str)

否则文本中任何“E”的隐藏都将被替换为“East”。作为替代方案,您至少可以在$ search和$ replace字符串中添加空格右侧。

答案 1 :(得分:1)

不要打扰正则表达式,只需按照更换较长字符串的顺序订购替换字符串:

$search = array("North Northeast", "East Northeast", "East Southeast", "South Southeast", "South Southwest", "West Southwest", "West Northwest", "North Northwest", "Northeast", "SouthEast", "Southwest", "Northwest", "North", "East", "South", "West");

$replace = array("NNE", "ENE", "ESE", "SSE", "SSW", "WSW", "WNW", "NNW", "NE", "SE", "SW", "NW", "N", "E", "S", "W");

echo str_replace($search, $replace, "East Northeast winds 20 knots");

// Output: ENE winds 20 knots

这样您就不必担心在East之前更换East Southeast

相关问题