php str_替换和\b字边界
我正在尝试使用str_replace,但不知道如何将\b用于单词边界:php str_替换和\b字边界,php,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", "S
<?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"
?>
不用担心正则表达式,只需按照先替换较长字符串的顺序来排序替换字符串:
$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-southerast
之前被替换您不能将\b与stru-replace()一起使用。单词boundary“\b”在正则表达式中只是一个有效的锚点。因此,使用preg_replace(),如果搜索文本包含自然语言,则更合适:
$replace = array_combine($search, $replace);
preg_replace('#\b('.implode('|',$search).')\b#e', '$replace["$1"]?:"$1"', $str)
否则,文本中任何“E”的出现都将被替换为“East”。作为替代方案,您至少可以在$search和$replace字符串中添加一个空格