Regex get first name out of "Aardal, Prof.dr.ir. K.I. (Karen)"
Can anyone help me write a regex to filter the name between parenthesis in a string like this: Aardal, Prof.dr.ir. K.I. (Karen)
I tried
preg_match('~[^/]([^/])~', $fullname, $matches);
var_dump($matches);
But the ret开发者_运维知识库urn is
array
0 => string 'Aa' (length=2)
1 => string 'a' (length=1)
Thanks guys!
- you can skip any character except the
(
- then match
(
and any character besides)
- then match
)
- between
(
and)
is now the capture-group "name"
Regex:
[^\(]*\((?<name>[^\)]+)\)
Tested with the tool Expresso. This regex matches two groups:
- The whole string: "Aardal, Prof.dr.ir. K.I. (Karen)"
- The named group 'name': "Karen"
Notes:
(?<name>...)
is the named group- To match the
(
etc. we have to escape it with a slash.
Some standard string functions would do it too:
function extractName($subject)
{
$openIndex = strpos($subject, '(');
if ($openIndex !== false)
{
$closeIndex = strpos(substr($subject, $openIndex + 1), ')');
if ($closeIndex !== false)
return substr($subject, $openIndex + 1, $closeIndex);
}
else
return '';
}
echo extractName('Aardal, Prof.dr.ir. K.I. (Karen)');
Try Following One
.*\((.*)\)
Then Capture First Group Value, Which will match following:
Aardal, Prof.dr.ir. K.I. (Karen)
精彩评论