phpregexhyperlinkpreg-replacemention

Replace @mentions with an HTML hyperlink


I have the following:

preg_replace('/\B@[^\B ]+/', '<a href="profile.php">$0</a>');

Which checks for any string that starts with @ and ends with a space and turns it into a link.

Now what I need is to create another preg_replace that would remove the @ symbol from the string, like @hello, so that it would just become hello.

I need this so that I can change the link in the first preg_replace to become <a href="profile.php?user=hello>$0</a>.


Solution

  • You can wrap part of your patern in () to create new variable In this case you will have your match string without @ under $1 variable

    preg_replace('/\B@([^\B ]+)/', '<a href="profile.php?profile=$1">$0</a>');
    

    Working example