Thomas Thomas - 2 months ago 11
PHP Question

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 return is

array
0 => string 'Aa' (length=2)
1 => string 'a' (length=1)


Thanks guys!

Answer
  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.