开发者

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!


  1. you can skip any character except the (
  2. then match ( and any character besides )
  3. then match )
  4. between ( and ) is now the capture-group "name"

Regex:

[^\(]*\((?<name>[^\)]+)\)

Tested with the tool Expresso. This regex matches two groups:

  1. The whole string: "Aardal, Prof.dr.ir. K.I. (Karen)"
  2. 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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜