Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php str_替换和\b字边界_Php - Fatal编程技术网

php str_替换和\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

我正在尝试使用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"

?>

不用担心正则表达式,只需按照先替换较长字符串的顺序来排序替换字符串:

$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 Southwest之前被替换。

您不能将\b与str\u replace一起使用。单词boundary\b仅是正则表达式中的有效锚点。因此,使用preg_replace,如果搜索文本包含自然语言,则更合适:

 $replace = array_combine($search, $replace);
 preg_replace('#\b('.implode('|',$search).')\b#e', '$replace["$1"]?:"$1"', $str)
否则,文本中的任何内容都将替换为East。作为替代方案,您至少可以在$search和$replace字符串中添加一个空格