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
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
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.
<?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
?>
^[^,]*,[^,]*\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
$s = "Hello, my name is David, bla bla.";
$s = explode(',', $s);
$s = explode(' ', $s[1]);
$test = $s[sizeof($s)-1];
print $test;
'David'
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;
?>