Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

PHP - Removing specific words from sentence

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would recommend using preg_replace instead of str_replace, using a regex that asserts a word boundary on either side of the words you want to remove. This will prevent it removing 10 in 90210 or 7 in 78665.

function get_weather_location($weather_location){
    $weatherwords = array("weather", "forecast", "temperature", "near", "for", "10", "ten", "7", "seven", "day");
    $weather_regex = '/(' . implode('|', $weatherwords) . ')/';
    $weather_location= preg_replace($weather_regex, "", $weather_location);
    $weather_location= trim($weather_location);
    return $weather_location;
}

Output:

90210
seattle, wa
78665

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...