tags:

views:

69

answers:

2

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"

?>
+1  A: 

Don't bother with the regexes, just order your replacement strings in an order that replaces the longer ones first:

$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

This way you don't have to worry about East being replaced before East Southeast.

Tatu Ulmanen
Thank you! Works like a charm...
Barry
@Barry, don't forget to mark the answer accepted then :)
Tatu Ulmanen
A: 

You cannot use \b with str_replace(). The word boundary "\b" is only a valid anchor in regular expressions. So use preg_replace(), it's more appropriate should your search text contain natural language:

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

Otherwise any occourence of "E" in the text will get replaced with "East". As alternative you could at least add a space right hand to your $search and $replace strings.

mario