I am trying to create a mention system and so far I've converted the @username in a link. But I wanted to see if it is possible for it to recognise whitespace for the names. For example: @Marie Lee
instead of @MarieLee
.
Also, I'm trying to convert the name in the link into lowercase letters (like: profile?id=marielee
while leaving the mentioned showed with the uppercased, but haven't been able to.
This is my code so far:
<?php
function convertHashtags($str) {
$regex = '/@+([a-zA-Z0-9_0]+)/';
$str = preg_replace($regex, strtolower('<a href="profile?id=$1">$0</a>'), $str);
return($str);
}
$string = 'I am @Marie Lee, nice to meet you!';
$string = convertHashtags($string);
echo $string;
?>
You may use this code with
preg_replace_callback
and an enhanced regex that will match all space separated words:If you want to allow only 2 words then you may use: