php - 从 PHP 数组中删除选定单词的有效方法

标签 php arrays keyword

我创建了一个数组来获取文件,然后解析该文件的内容。我已经用 if(strlen($value) < 4): unset($content[$key]); endif; 过滤掉了少于 4 个字符的单词

我的问题是 - 我想从数组中删除常用词,但其中有很多。我想知道是否有更有效的方法来执行此操作,而不是对每个数组值一遍又一遍地进行这些检查?

这是我目前正在使用的代码示例。这个列表可能很大,我认为必须有更好(更有效)的方法吗?

foreach ($content as $key=>$value) {
    if(strlen($value) < 4): unset($content[$key]); endif; 
    if($value == 'that'): unset($content[$key]); endif;
    if($value == 'have'): unset($content[$key]); endif;
    if($value == 'with'): unset($content[$key]); endif;
    if($value == 'this'): unset($content[$key]); endif;
    if($value == 'your'): unset($content[$key]); endif;
    if($value == 'will'): unset($content[$key]); endif;
    if($value == 'they'): unset($content[$key]); endif;
    if($value == 'from'): unset($content[$key]); endif;
    if($value == 'when'): unset($content[$key]); endif;
    if($value == 'then'): unset($content[$key]); endif;
    if($value == 'than'): unset($content[$key]); endif;
    if($value == 'into'): unset($content[$key]); endif;
}

最佳答案

这是我的做法:

$exlcuded_words = array( 'that','have','with','this','your','will','they','from','when','then','than','into');
$replace = array_fill_keys($exlcuded_words,'');
echo str_replace(array_keys($replace),$replace,'some words that have to be with this your will they have from when then that into replaced');

它的工作方式:创建一个充满空字符串的数组,其中的键是您要删除/替换的子字符串。只需使用 str_replace,将键作为第一个参数传递,将数组本身作为第二个参数传递,在这种情况下的结果是:一些要替换的单词。此代码已经过测试并且工作正常。

当处理一个数组时,只需用一些古怪的分隔符(比如 %@%@% 或其他东西)和 str_replace 来分解它,再次分解它并且Bob 是你的叔叔


当谈到用少于 3 个字符替换所有单词时(我在原来的答案中忘记了),这是正则表达式擅长的...我会说类似 preg_replace('(\b|[^a-z])[a-z]{1,3}(\b|[^a-z])/i','$1$2',implode(',',$targetArray)); 或某事像那样。
你可能想测试一下这个,因为这只是我的想法,还没有经过测试。但这似乎足以让你开始

关于php - 从 PHP 数组中删除选定单词的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11812586/

相关文章:

javascript - 如何将多维数组转换为单个数组? JavaScript

java - 不带循环的整数数组交集递归

javascript中的java关键字

c++ - 函数返回类型和名称之间存在未知关键字

php - MySQL 使用第二个表中的条件构建查询

php - WordPress自定义mysql查询不带IN()排序

c - 如何增加每个循环中具有全局指针的数组大小

php - 未更新 VirtueMart 2 数据库中产品中的新字段

javascript - 将 HTML 表的每一行放入不同的数组中

java - 如何在java中引用外部文件的关键字