str_word_count

  • There is no native way to count the number of words in a Ruby string. Instead we would use the String#scan method to split a string based on a regular expressionw word boundary, and find the length of the results.

    PHP

    print str_word_count("hello world");
    // => 2

    Ruby

    puts "hello world".scan(/\w+/).length
    # => 2

    see also

str_split strchr

Looking for Rails or PHP web application development, integration, and training?

Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.