php str_replace and \b word boundary

Posted by Barry on Stack Overflow See other posts from Stack Overflow or by Barry
Published on 2010-06-08T04:51:14Z Indexed on 2010/06/08 5:02 UTC
Read the original article Hit count: 426

Filed under:

Hi, I am trying to use str_replace, but can't figure out how to use \b for word boundary:

<?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"

?>

© Stack Overflow or respective owner

Related posts about php