tags:

views:

126

answers:

6

I want to store the word before the second comma in a string.

So if the string looks like this: Hello, my name is David, bla bla.

I want to set a variable $test = David

+1  A: 

this is web based nice tool which name is txt2re

javaloper
+3  A: 

Your regex could look something like this:

^[^,]*,[^,]*\b(\w+),

Match any sequence of non-commas, followed by the first comma, followed by more non-commas, then a word boundary and your actual word, and then the second comma.

Thomas
word boundary is `\b` - `\w` is word itself
Amarghosh
Good point, thanks.
Thomas
`\w` is a word character, not a word boundary. `[^,]` is any character that is not a comma, not a word character.
Svante
also you might wanna consider capturing `(\w+)` instead of `([^,]*)` as the later matches even an empty string. When tested with Expresso, this regex matched the word boundary and empty string after David.
Amarghosh
You're right. Now it's nearly the same as Svante's solution, which I upvoted anyway because his explanation is much nicer.
Thomas
removed the down-vote :)
Amarghosh
A: 
<?php

    $s = "Hello, my name is David, bla bla.";

    preg_match ( "/[^,]*,[^,].* ([^,].*),.*/" , $s, $matches ); 

    // or shorter ..
    preg_match ( "/[^,]*,[^,]*\b(\w+),/" , $s, $matches );

    echo $matches[1];
    // => David

?>
The MYYN
+3  A: 
^[^,]*,[^,]*\b(\w+)\b,

^ -- The beginning of the string/line
[^ ] -- Any character not being ...
, -- ... a comma
* -- Zero or more of the preceding
, -- A comma
[^,]* -- Again, any character not being a comma, repeated zero or more times
\b -- A word boundary (zero width)
( ) -- A capturing group
\w -- Any word character
+ -- One or more of the preceding
\b -- A word boundary (zero width)
, -- A comma

Svante
A: 
$s = "Hello, my name is David, bla bla.";
$s = explode(',', $s);
$s = explode(' ', $s[1]);
$test = $s[sizeof($s)-1];

print $test;
'David'
Tor Valamo
A: 

And here is my approach:

<?php
    $input  = 'Hello, my name is David, bla bla.';
    $tmp    = substr( $input, 0, strpos( $input, ',', strpos( $input, ',' ) + 1 ) );
    $word   = substr( $tmp, strrpos( $tmp, ' ' ) + 1 );
    echo $word;
?>
MiB