You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP校验字符串中每个单词的长度均不小于指定最小值

PHP校验所有单词长度不小于指定值的实现方案

核心实现思路

先将字符串按空格拆分为单词数组,遍历校验每个单词长度即可,符合要求返回true后就可以执行对应业务操作,以下是可直接复用的函数:

/**
 * 校验字符串中所有单词长度是否均不小于指定阈值
 * @param string $inputStr 待校验字符串,单词以空格分隔
 * @param int $minLength 要求的单词最小长度
 * @return bool 所有单词符合要求返回true,否则返回false
 */
function checkAllWordsMinLength(string $inputStr, int $minLength): bool
{
    // 按空格拆分字符串,过滤空值(避免连续空格、首尾空格产生无效空元素)
    $words = array_filter(explode(' ', $inputStr));
    foreach ($words as $word) {
        // 多字节场景用mb_strlen,纯英文可替换为strlen性能更高
        if (mb_strlen($word) < $minLength) {
            return false;
        }
    }
    return true;
}

使用示例

// 校验所有单词长度不小于5的场景
$testStr = 'apple banana orange grape';
if (checkAllWordsMinLength($testStr, 5)) {
    // 所有单词符合要求时执行对应操作
    echo '所有单词长度均满足要求';
} else {
    echo '存在长度不足的单词';
}

基于str_word_count的适配版本

如果你的场景是纯英文单词,不需要兼容中文、数字等内容,可以用你熟悉的str_word_count实现,该方法会自动识别英文单词,过滤符号、数字内容:

function checkAllWordsMinLengthV2(string $inputStr, int $minLength): bool
{
    $words = str_word_count($inputStr, 1);
    foreach ($words as $word) {
        if (strlen($word) < $minLength) {
            return false;
        }
    }
    return true;
}

内容的提问来源于stack exchange,提问作者ShadowAccount

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 05:27:03