I'm trying to extract a location from common phrases about the weather using PHP. My current approach is using str_replace()
, but it is having some unintended results. Parts of zip codes are being replaced because str_replace()
is replacing part of the zip code while searching for "10 day" or "7 day" forecast
$weather_location_1 = "10 day forecast for 90210";
$weather_location_2 = "weather near seattle, wa";
$weather_location_3 = "temperature 78665";
function get_weather_location($weather_location){
$weatherwords = array("weather", "forecast", "temperature", "near", "for", "10", "ten", "7", "seven", "day");
$weather_location= str_replace($weatherwords, "", $weather_location);
$weather_location= trim($weather_location);
return $weather_location;
}
$weather_location_1 = get_weather_location($weather_location_1);
echo $weather_location_1; // returns "902", but I want it to return 90210
$weather_location_2 = get_weather_location($weather_location_2);
echo $weather_location_2; // returns "seattle, wa", works as intended
$weather_location_3 = get_weather_location($weather_location_3);
echo $weather_location_3; // returns "8665", but I want it to return 78665
What should I use instead of str_replace()
so that parts of the zip code aren't replaced, only each complete word in the $weatherwords
array, and not "10" or "7" from zipcodes? Instead of str_replace()
, I'm looking for word_replace()
or something that just replaces each word in $weatherwords
, not all matching substrings.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…