Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Mar 2008
    Posts
    61
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Preg match question

    So say if

    $sentence = "Hello Bob , How are you doing";

    How do i basically get it to echo only "Bob" from $sentence (so basically echo only the thing in between "Hello" and " , How are you doing"

  • #2
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    Quote Originally Posted by WebmasterLULZ View Post
    So say if

    $sentence = "Hello Bob , How are you doing";

    How do i basically get it to echo only "Bob" from $sentence (so basically echo only the thing in between "Hello" and " , How are you doing"
    PHP Code:
    $sentence  "Hello Bob , How are you doing";
    echo 
    preg_replace("/^Hello\s+(.+)[,\s]*How are you doing$/","$1",$sentence); 
    not tested.

    regards

  • #3
    Regular Coder ninnypants's Avatar
    Join Date
    Apr 2008
    Location
    Utah
    Posts
    504
    Thanks
    10
    Thanked 47 Times in 47 Posts
    PHP Code:
    $sentence "Hello Bob, How are you doing";
    $match '/^Bob/';
    preg_match($match,$sentence,$match);
    echo 
    $match[1]; 
    something similar to that.
    PHPmanual

  • #4
    New Coder
    Join Date
    May 2006
    Posts
    62
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by WebmasterLULZ View Post
    So say if

    $sentence = "Hello Bob , How are you doing";

    How do i basically get it to echo only "Bob" from $sentence (so basically echo only the thing in between "Hello" and " , How are you doing"
    PHP Code:
    $match preg_match("/hello(.+?),/i"$sentence$matches);
    if (
    $match) {
      
    $match trimmatches[1] );
    }

    // $match will hold either boolean FALSE or the matched name.. 
    The match is made in (.+?) which will be saved to $matches[1].
    the . matches any character. The + means the left match can be either once or more. The ? means match the left match non-greedily or until the 1st right match is made.

    You can also use the regular expression:
    Code:
    "/hello ([^,]+)/"
    The regular expression engine is a lot slower then using just using string functions however. So you could use:
    Code:
    list($greeting, $name) = explode(" ", $sentence);
    And $name will be the name. Thats assuming the name is always the second word.
    Last edited by digital-ether; 07-24-2008 at 09:24 AM.
    Fiji Web Design - where i do Joomla Web Design
    Bucabay.com - My blog


  •  

    Posting Permissions

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