繁体   English   中英

PHP - 从句子中删除特定单词

[英]PHP - Removing specific words from sentence

我正在尝试使用 PHP 从有关天气的常用短语中提取位置。 我目前的方法是使用str_replace() ,但它有一些意想不到的结果。 正在替换部分 zip 代码,因为str_replace()在搜索“10 天”或“7 天”预测时替换了部分 zip 代码

$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

我应该使用什么来代替str_replace()以便不替换 zip 代码的部分,仅替换$weatherwords数组中的每个完整单词,而不是邮政编码中的“10”或“7”? 而不是str_replace() ,我正在寻找word_replace()或仅替换$weatherwords weatherwords 中的每个单词的东西,而不是所有匹配的子字符串。

我建议使用preg_replace而不是str_replace ,使用正则表达式在要删除的单词的任一侧断言单词边界。 这将防止它删除90210中的1078665中的7

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

Output:

90210
seattle, wa
78665

首先,您必须找到模式。

我的意思是:请考虑一个模式,你可以告诉你 7 岁的女儿转换或提取所需的数据。 她只知道这个模式和原始数据。 就像印刷报纸和一些基本规则。 她不知道“天气”或预报是什么,但她可以阅读文字。 计算机的智能不如一个 7 岁的孩子。 ;-)

您目前正在做的事情没有帮助。 如果您将 ZIP 代码中的 7 替换为空代码,您将在地狱中结束。 那是没有可用的模式。

也许你只会有几个或 100 种不同的模式,比如“XXXXXXX 的 Z(Z) 天预测”; X在哪里? 和?

“XXXXXX,ZZ 附近的天气”也将是人类和计算机可以理解的模式。

如果您已经定义了所有这些模式,那么您可以将它们转换为正则表达式并检查它们是否会正确转换现实生活中的数据。

主题正则表达式相当复杂,上面写了很多书。 所以没有这样的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM