简体   繁体   中英

preg_replace() with a link

I am trying to integrate a reply system like Twitter, where you can use "@usernameHere". I need to replace @usernameHere with a link to that user's profile. Can I do it with just preg_replace() . Something like this...?

$pattern = '/(?<![\w@])@([\w@]+(?:[.!][\w@]+)*)/';
$replacement = '<a href="profile?user='.$needle.'">Username</a>';
$string = "@mark, hey wanna hang?";
preg_replace($pattern, $replacement, $string);

How would I get the $needle ? As in, how would I get the contents of what was replaced? The $needle in this situation would be mark

Is there anyway I could get it like preg_match() ? Here is how I would get it with preg_match() .

preg_match('/(?<![\w@])@([\w@]+(?:[.!][\w@]+)*)/', $comment, $matches);
$matches[1] = $needle;

The documentation states this clearly:

replacement may contain references of the form \\n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 or $0 refers to the text matched by the whole pattern . Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern. To use backslash in replacement, it must be doubled ("\\\\" PHP string).

$n in regular expression replacements are references to what was matched by the nth capturing group .

So you would use $1 here to reference what was matched by the first capturing group.

$replacement = '<a href="profile?user=$1">$1</a>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM