Thomas Thomas - 1 year ago 72
PHP Question

Regex get first name out of "Aardal, K.I. (Karen)"

Can anyone help me write a regex to filter the name between parenthesis in a string like this:

Aardal, K.I. (Karen)

I tried

preg_match('~[^/]([^/])~', $fullname, $matches);

But the return is

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

Thanks guys!

Answer Source
  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"



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

  1. The whole string: "Aardal, K.I. (Karen)"
  2. The named group 'name': "Karen"


  • (?<name>...) is the named group
  • To match the ( etc. we have to escape it with a slash.