I am working on a project and am trying to add the ability to detect hashtags and tagged users.
The problem is I don't know how to make it stop reading when it reaches symbols or emojis (Except underscores) and not let the length go over 20 characters
For hashtags
#HelloWorld -> helloworld, #Hello_W0rld -> hello_w0rld, #Hello(World -> hello,
Also for tagged users (Which only allows A-Z a-z 0-9 and _
@HelloWorld -> helloworld, @Hello_W0rl.d -> hello_w0rl
My attempted code is (basically same for users or hashtags)
$words = explode(" ", $body);
foreach($words as $word){
if(substr($word, 0, 1) == "@"){
$tagged_user = DB::query('SELECT id FROM users WHERE username=:username', array(':username' => ltrim($word, '@')))[0];
$users .= $tagged_user,",";
}
}
$users = rtrim($users, ',');
Also would it know not to save #%
as a blank space
Edit: I updated it to this, is this correct?
$postid = "test_id";
$matches = [];
preg_replace_callback("/#([a-z_0-9]+)/i", function($res) use(&$matches) {
$matches[] = strtolower($res[1]);
}, $body);
$matches2 = [];
$tagholder = array_fill(0, count($matches), "?");
$tagholderString = implode(", ", $tagholder);
foreach($matches as $tagstring){
if(DB::query('SELECT * FROM tags WHERE tag=:tag', array(':tag' => $tagstring))){
$tag = DB::query('SELECT * FROM tags WHERE tag=:tag', array(':tag' => $tagstring))[0];
DB::query ( "INSERT INTO post_tags VALUES(:tagid, :postid)", array (':tagid' => $tag['id'], ':postid' => $postid) );
}else{
$id = hash(sha256, $tagstring);
DB::query ( "INSERT INTO tags VALUES(:id, :tag, :mode)", array (':id' => $id, ':tag' => $tagstring, ':mode' => 0) );
DB::query ( "INSERT INTO post_tags VALUES(:tagid, :postid)", array (':tagid' => $id, ':postid' => $postid) );
}
}
preg_replace_callback("/@([a-z_0-9]+)/i", function($res) use(&$matches2) {
$matches2[] = strtolower($res[1]);
}, $body);
$userholder = array_fill(0, count($matches2), "?");
$userholderString = implode(", ", $userholder);
$user_query = DB::query("SELECT * FROM users WHERE username IN (".$userholderString.")", $matches2);
$users_result = "";
foreach($user_query as $result){
$users_result .= $result['id'].",";
}
$users_result = rtrim($users_result, ',');
//User string result
$users_result;