You can use a capturing group ( )
around your pattern you want captured to separate the captured match and the whole string. You can then place your captured match $1
where you desire and use $0
to access your whole string match.
preg_replace('/\B@(\S+)/', '<a href="profile.php?profile=$1">$0</a>', $str);
You can use \S
here instead. I don't recommend using \B
inside of a negated character class.
Regular expression:
\B the boundary between two word chars (\w)
or two non-word chars (\W)
@ '@'
\S+ non-whitespace (all but \n, \r, \t, \f, and " ") (1 or more times)
See a working demo