PHP在数据库表中注册3个Hashtags

时间:2016-07-21 07:16:42

标签: php mysql

enter image description here

你好,我有一个字符串,我想在数据库中注册,如下所示: enter image description here

我的代码不起作用

function find_hashtags($string) {
        $hashtags = FALSE;  
        preg_match_all("/(#\w+)/u", $string, $matches);  
        if ($matches) {
            $hashtags = implode(' , ', $matches[0]);
        }
        return $hashtags;
    }
$my_string = 'blabla #a ehehhe #b #c';
$find_hashtags = find_hashtags($my_string);
mysqli_query($Conn, "INSERT INTO `hashtags`(`post_id`, `hashtag`, `used`) VALUES ('$last_post_id', '$find_hashtags', '1')");    

1 个答案:

答案 0 :(得分:3)

1

不是在find_hashtag()函数中创建字符串,而是创建一个数组。

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

现在返回一个数组。

2

然后遍历数组并INSERT数组的每一行。

$my_string = 'blabla #a ehehhe #b #c';
$hashtags = find_hashtags($my_string);
foreach($hashtags as $hashtag) // Looping the array
{
    mysqli_query($Conn, "INSERT INTO `hashtags`(`post_id`, `hashtag`, `used`) VALUES ('$last_post_id', '$hashtag', '1')");
}

您可能需要对此进行一些调整,但现在,$hashtags是一个包含字符串每个标签的数组。

请询问是否有不清楚的事情,或者您是否需要进一步的帮助。