...

View Full Version : Preg match question



WebmasterLULZ
07-24-2008, 12:19 AM
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"

oesxyl
07-24-2008, 12:27 AM
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"



$sentence = "Hello Bob , How are you doing";
echo preg_replace("/^Hello\s+(.+)[,\s]*How are you doing$/","$1",$sentence);


not tested.

regards

ninnypants
07-24-2008, 12:32 AM
$sentence = "Hello Bob, How are you doing";
$match = '/^Bob/';
preg_match($match,$sentence,$match);
echo $match[1];

something similar to that.
PHPmanual (http://us2.php.net/manual/en/function.preg-match.php)

digital-ether
07-24-2008, 09:20 AM
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"


$match = preg_match("/hello(.+?),/i", $sentence, $matches);
if ($match) {
$match = trim( matches[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:

"/hello ([^,]+)/"

The regular expression engine is a lot slower then using just using string functions however. So you could use:


list($greeting, $name) = explode(" ", $sentence);

And $name will be the name. Thats assuming the name is always the second word.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum