Php 如何替换“on,in,or,and,of”

Php 如何替换“on,in,or,and,of”,php,Php,我有这样的绳子 $string = "the man on the platform" 然后我修剪并删除空白 $words = explode(' ', trim(preg_replace('/\s+/', ' ', $string))); print_r($words); 结果 Array ( [0] => the [1] => man [2] => on [3] => the [4] => platform) 如何删除“on”和“the”以获得这

我有这样的绳子

$string = "the man on the platform"
然后我修剪并删除空白

$words =    explode(' ', trim(preg_replace('/\s+/', ' ', $string)));

print_r($words);
结果

Array ( [0] => the [1] => man [2] => on [3] => the [4] => platform) 
如何删除“on”和“the”以获得这样的结果,以便以后在DB中循环和搜索

Array ( [0] => man [1] => platform)

实现所需结果的一种方法是与要删除的停止词列表一起使用:

$string = "the man on the platform";
$words =  preg_split('/\s+/', $string);
$stop_words = array('on', 'in', 'or', 'and', 'of', 'the');
$words = array_filter($words, function ($v) use ($stop_words) { return !in_array($v, $stop_words); });
print_r($words);
输出:

Array
(
    [1] => man
    [4] => platform
)
请注意,与使用preg_replace将空间集转换为单个空间然后调用explode不同,您可以只使用并拆分一组空间

此外,您还可以通过将停止字用作数组中的键,使其稍微更有效,从而允许在筛选函数中使用isset而不是in_数组:

$stop_words = array('on' => 1, 'in' => 1, 'or' => 1, 'and' => 1, 'of' => 1, 'the' => 1);
$words = array_filter($words, function ($v) use ($stop_words) { return !isset($stop_words[$v]); });

您可以稍后测试哪个更快,但我认为最好是在正则表达式上处理所有内容,而不是分解字符串,然后在其上使用数组函数。这项工作非常完美,无论如何,我也可以匹配单词末尾的“t”,如“不”,或开头的“x”x100@GameClubStreaming我不知道你到底是什么意思?是否要删除以“t”结尾的单词和以“x”开头的单词(如x100)?但是木琴呢?对不起,这是个坏例子,我指的是像女人的变成女人或者像x100的变成女人100@GameClubStreaming你必须做一些正则表达式替换。类似这样的问题可能是一个很好的起点:,如果你不能让它工作,我建议你问一个新问题,因为它与这个问题完全不同。