Search code examples
phppreg-matchpreg-match-all

Replacing @tags from form input with values from the database


I am writing an @tagging system in which someone posts some text inside a comment box like: Please @mike read this. @paul also. Then the comments appears with the @tags replaces with values selected from a particular database containing @tags and their actual values. The comments then appear like this: Please Mike Smith read this. Paul Hay also. The @tags will be replaced with values from the database.

This is what I have done so far.

$comments = "Please @mike read this. @paul also";
$pattern = '/\B@[^\B]+/';
preg_match_all($pattern, $comments, $matches);
foreach ($matches[0] as $key => $value) {

$sql = "SELECT * FROM user_table WHERE tagged = '$value[$key]'";
foreach ($pdo ->query($sql) as $row){
$name = $row['name'];
$username = $row['username'];
$comments = preg_replace('/[@]+([A-Za-z0-9-_]+)/', '<a href='.$username.'>'.$name.'</a>', $comments );
}
echo $comments;}

So far, this is not outputting anything reasonable, rather what it gives is just the plain comments. Please correct me where necessary. Thank you all


Solution

  • Try this

    $comments = "Please @mike read this. @paul also";
    $pattern = '/@[a-zA-Z0-9_]+/'; # Changed
    preg_match_all($pattern, $comments, $matches);
    
    # print_r($matches[0]); --Output> Array ( [0] => @mike [1] => @paul )
    
    foreach ($matches[0] as $key => $value) {   
    
        $newValue = str_replace('@'," ", $value);# added
    
        # echo $newValue; --Output> mike paul
    
        $sql = "SELECT * FROM user_table WHERE tagged = '$newValue' "; # Changed
    
        foreach ($pdo->query($sql) as $row){
    
            $name = $row['name'];
            $username = $row['username'];
            $link = "<a href=".$username.">".$name."</a>"; # added
            $comments = preg_replace('@', $link, $comments );
    
        }
    
        echo $comments;
    
    }