Genti Genti - 4 months ago 30
PHP Question

PHP Find Hashtags In String And Insert Into Database

I want to find all hashtags from a string and insert them into a table (sql).

$string = "hello #hashtag_1 bla bla #hashtag_2";


I don't have idea how to do this. Any ideas?

function getHashtags($string) {
$hashtags= FALSE;
preg_match_all("/(#\w+)/u", $string, $matches);
if ($matches) {
$hashtagsArray = array_count_values($matches[0]);
$hashtags = array_keys($hashtagsArray);
}
return $hashtags;
}

Answer

Well when you return $hashtags, it is returned as an array

Array
(
    [0] => #hashtag_1
    [1] => #hashtag_2
)

You need to combine the array into a string. Use this as your getHashtags() function (I chose to have it be comma separated but you can choose other delimiters)

function getHashtags($string) {  
    $hashtags = FALSE;  
    preg_match_all("/(#\w+)/u", $string, $matches);  
    if ($matches) {
        $hashtags = implode(",", $matches[0]);
    }
    return $hashtags;
}

$hashtags would return #hashtag_1,#hashtag_2 and then your $sql_query should change to

$sql_query = mysqli_query($conn, "INSERT INTO hashtags VALUES('" . getHashtags($string) . "')")

Also be sure to add a check if $hashtags != FALSE so it only inserts into database if there is a hashtag

So here is the full code:

function getHashtags($string) {  
    $hashtags = FALSE;  
    preg_match_all("/(#\w+)/u", $string, $matches);  
    if ($matches) {
        $hashtags = implode(",", $matches[0]);
    }
    return $hashtags;
}

$hashtags = getHashtags($string);
if($hashtags != FALSE) {
    $sql_query = mysqli_query($conn, "INSERT INTO hashtags VALUES('" . $hashtags . "')")
}