2010-06-08 4 views
2

내가 않는 str_replace를 사용하려고하지만, 단어 경계에 대한 \ B를 사용하는 방법을 알아낼 수 없습니다 :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" 

?> 

답변

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 

당신에 대한 EastEast Southeast 전에 교체 걱정하지 않아도 이쪽으로.

+0

고맙습니다! 매력처럼 작동합니다 ... – Barry

+0

@ 배리, 다음 답변을 표시하는 것을 잊지 마세요 :) –

2

str_replace()에는 \ b를 사용할 수 없습니다. 단어 경계 "\ b"는 정규식에서 유효한 앵커 일뿐입니다.

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

은 그렇지 않으면 텍스트에서 "E"의 occourence은 "동"으로 대체 얻을 것이다 : 그래서 preg_replace이다()를 사용, 그것은 당신의 검색 텍스트는 자연 언어를 포함해야 더 적합합니다. 대안으로 적어도 $ 검색에 스페이스 오른손을 추가하고 $ 문자열을 바꿀 수 있습니다.