php str_replace and \b word boundary

前端 未结 2 998
旧时难觅i
旧时难觅i 2021-01-22 05:14

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



        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-22 05:16

    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.

提交回复
热议问题