Thread: String Length

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2015
    Posts
    4
    Rep Power
    0

    String Length


    Hi,

    I am trying to get an accurate count characters in a string. I know you can use strlen but that I believe counts bytes not characters. I dont want any line breaks or tabs to be counter just the any characters including symbols.

    Thanks in advance.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Posts
    4,108
    Rep Power
    601
    PHP Code:
    $count=strlen(preg_replace('/\s+/','',$string)); 
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2015
    Posts
    4
    Rep Power
    0
    Thanks for the reply, that looks to just remove spaces. I shoud have said I need to count space too. Any kind of character, symbol and space but no line breaks.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Posts
    4,108
    Rep Power
    601
    That will remove all white space. If you want to keep spaces then adjust the regexp for the characters you don't want to count.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jul 2003
    Posts
    4,108
    Rep Power
    601
    Thinking about it, this might be easier:
    PHP Code:
    $count=strlen(preg_replace('[^a-Z\d\s]','',$string)); 
    If your strings have punctuation you would need to add those to the regexp.
    Last edited by gw1500se; November 16th, 2015 at 06:43 AM.
    There are 10 kinds of people in the world. Those that understand binary and those that don't.
  10. #6
  11. Subconscious Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    15,470
    Rep Power
    9565
    [^a-Z] will also incorrectly exclude [ \ ] ^ _ `

    The two letter sets have to be separate.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2015
    Posts
    4
    Rep Power
    0
    I figured it out in the end using this..

    PHP Code:
    $value preg_replace('!s:(\d+):"(.*?)";!e'"'s:'.strlen(stripcslashes('$2')).':\"$2\";'"$value ); 
    Thanks.

IMN logo majestic logo threadwatch logo seochat tools logo