SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Feel my RewiredMind KMxRetro's Avatar
    Join Date
    Jan 2001
    Location
    Exeter, Devon, UK
    Posts
    477
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi there,
    Could anyone tell me if it is possible to find all instances of capitalized words in a string?

    For instance, if I had the following...

    $work = "Hello, my name is Ken";

    I would need to pull the words "Hello" and "Ken" from the string.

    Is that possible in PHP?

    Thanks,

  2. #2
    SitePoint Zealot cokeman's Avatar
    Join Date
    Dec 2000
    Location
    So. California
    Posts
    173
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could tokenize the string (separator being spaces) and use regular expressions to check if each token begins with an uppercase letter.

    PHP Code:
    <?
    $string 
    "Hello, my name is Ken";
    $tok strtok ($string," ");
    while (
    $tok) {
        echo 
    "Word=$tok";
        if (
    ereg ("^[A-Z]"$tok))
           echo 
    " (uppercase)";   
        echo 
    "<br>\n";
        
        
    $tok strtok (" ");
    }
    ?>

  3. #3
    Feel my RewiredMind KMxRetro's Avatar
    Join Date
    Jan 2001
    Location
    Exeter, Devon, UK
    Posts
    477
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That oughta do it!

    Thanks very much

  4. #4
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Another slightly different but equally as effective:

    PHP Code:
    function get_uc($str) {
        
    $data explode(" "$str);
        foreach(
    $data as $key => $val) {
            if (
    ereg("^[A-Z]"$val)) {
                
    $ucwords[] = $val;
                }
            }
        return 
    $ucwords;
        }




    $work "Hello, my name is Ken"
    $args get_uc($work);
    if (
    count($args) > 0) {
        foreach(
    $args as $key => $val) {
            print 
    "$val<br>";
            }
        }
    else {
        print 
    "there were no uppercase words in this string";
        } 
    Please don't PM me with questions.
    Use the forums, that is what they are here for.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •