php checking chars help

Posted on 2007-10-11
Last Modified: 2010-05-19
Does anyone have a function to check for spaces and to make sure length is not over 20 chars?
Question by:casit
    LVL 20

    Expert Comment


    function wordcount($str) {  
      return count(explode(" ",$str));

    // Example Usage:
    $test = "This String has five words.";
    echo "There are " . wordcount($test) . " in the sentence";

    Author Comment

    @gawai  Not what I was lookin for.  I was looking for something that checked a string to see if it had spaces OR if it was over 20 characters.
    LVL 9

    Accepted Solution

    Use strlen, it gives you the string length in characters. Here is your example :

    function has_space ( $str ) {
      $space_pos = strpos ( $str, " " );
      return $space_pos!==false;

    function check_string ( $str ) {
      $length = strlen ( $str );
      $space = has_space ( $str );
      return ( $length<=20 ) &&  ! $space;;


    Author Comment


    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    The Client Need Led Us to RSS I recently had an investment company ask me how they might notify their constituents about their newsworthy publications.  Probably you would think "Facebook" or "Twitter" but this is an interesting client.  Their cons…
    Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
    Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    731 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now