how to count the words in a specific string in PHP?

前端 未结 9 1546
忘了有多久
忘了有多久 2020-12-18 21:45

I want to count the words in a specific string , so I can validate it and prevent users to write more than 100 words for example .

I wrote this function but I don\'t

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 21:51

    You can use the built in PHP function str_word_count. Use it like this:

    $str = "This is my simple string.";
    echo str_word_count($str);
    

    This will output 5.

    If you plan on using special characters in any of your words, you can supply any extra characters as the third parameter.

    $str = "This weather is like el ninã.";
    echo str_word_count($str, 0, 'àáã');
    

    This will output 6.

提交回复
热议问题