Try this:
preg_replace( '/^\W*(.*?)\W*$/', '$1', $string )
/* -----------------------------------------------------------------------------------
^ the beginning of the string
\W* non-word characters (all but a-z, A-Z, 0- 9, _) (0 or more times (matching the most amount possible))
( group and capture to \1:
.*? any character except \n (0 or more times(matching the least amount possible))
) end of \1
\W* non-word characters (all but a-z, A-Z, 0-9, _) (0 or more times (matching the most amount possible))
$ before an optional \n, and the end of the string
------------------------------------------------------------------------------------- */