我有这样的字符串
$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"以获得这样的结果,以便以后在数据库中循环和搜索
Array ( [0] => man [1] => platform)
实现所需结果的一种方法是将array_filter
与非索引字(要删除的单词(列表一起使用:
$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
,不如只使用preg_split
并在一组空格上进行拆分。
此外,您可以通过在数组中使用停用词作为键来提高效率,允许在过滤器函数中使用isset
而不是in_array
:
$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]); });
3v4l.org 演示