根据 php 中的单词长度从字符串中删除单词


Remove Words From String based on word length in php

我想删除字符串中超过 2 个字母的单词。例如:

$string = "tx texas al alabama ca california";

我想删除那些超过两个字符的单词,因此输出如下所示: $output = "tx al ca";

echo preg_replace('/[a-z]{3,}/','',$string);

可能不是最好的解决方案,但你可以用空格作为分隔符分解字符串,遍历它,创建一个新数组,如果长度小于 2,则将单词推送到它:

$string = "tx texas al alabama ca california";
$words = explode(' ', $string);
foreach ($words as $word) {
    if(strlen($word) <= 2) {
        $result[] = $word; // push word into result array
    }
}
$output = implode(' ', $result); // re-create the string

输出:

tx al ca

演示!