Space in @ mention username and lowercase in link

338 views Asked by At

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;

?>
2

There are 2 answers

1
anubhava On BEST ANSWER

You may use this code with preg_replace_callback and an enhanced regex that will match all space separated words:

define("REGEX", '/@\w+(?:\h+\w+)*/');

function convertHashtags($str) {
    return preg_replace_callback(REGEX, function ($m) {
       return '<a href="profile?id=' . strtolower($m[0]) . '">$0</a>';
    }, $str);

}

If you want to allow only 2 words then you may use:

define("REGEX", '/@\w+(?:\h+\w+)?/');
7
nice_dev On

You can filter out usernames based on alphanumeric characters, digits or spaces, nothing else to extract for it. Make sure that at least one character is matched before going for spaces to avoid empty space match with a single @. Works for maximum of 2 space separated words correctly for a username followed by a non-word character(except space).

<?php
function convertHashtags($str) {
    $regex = '/@([a-zA-Z0-9_]+[\sa-zA-Z0-9_]*)/';
    if(preg_match($regex,$str,$matches) === 1){
        list($username,$name) = [$matches[0] , strtolower(str_replace(' ','',$matches[1]))];
        return "<a href='profile?id=$name'>$username</a>";
    }
    throw new Exception('Unable to find username in the given string');
}

$string = 'I am @Marie Lee, nice to meet you!';
$string = convertHashtags($string);
echo $string;

Demo: https://3v4l.org/e2S8C


If you want the text to appear as is in the innerHTML of the anchor tag, you need to change

list($username,$name) = [$matches[0] , strtolower(str_replace(' ','',$matches[1]))];

to

list($username,$name) = [$str , strtolower(str_replace(' ','',$matches[1]))];

Demo: https://3v4l.org/dCQ4S