System hashtags in PHP

4

I'm developing a hashtags system in PHP , and my question is:

How can I make a% of% of posts from content?

For example, the content saved in the database is:

  

Hi, how are you? #bomdia

In case the SELECT would be something like SELECT ?

I saw several articles where, when saving the publication to the database, all detected hashtags are saved in a separate column in the table, for example "hashtags".

What is the best way to do this?

    
asked by anonymous 28.05.2015 / 01:52

1 answer

6

As mentioned in the comments, the ideal is to separate the tag from the message. I would go a little further and make a table just for the tags, taking into account that a message can have several or no tags:

PleasenotethatI'veaddedanindexoftypeUNIQUEinthetagnametoavoidduplicatesandspeedupsearches.

Toextractthetagsfromthemessageuse preg_match_all() , saving in the database only the text of the tag, without the cerch ( # ):

<?php

class Mensagem {

    protected $mensagem;
    protected $tags = [];

    public function __construct($messagem)
    {
        $this->mensagem = $messagem;
        $this->extractTags($messagem);
    }

    private function extractTags($mensagem)
    {
        // Casa tags como #dia #feliz #chateado
        // Não casa caracteres especias #so-pt
        $pattern = '/#(\w+)/';

        // Alternativa para incluir outros caracteres
        // Basta incluir entre os colchetes
        //$pattern = '/#([\w-]+)/';

        preg_match_all($pattern, $mensagem, $tags);

        // Utiliza o vetor com os grupos capturados entre parenteses
        $this->tags = $tags[1];
    }

    public function getMensagem()
    {
        return $this->mensagem;
    }

    public function getTags()
    {
        return $this->tags;
    }

}

To use the class:

$mensagem = "Partiu #ferias #praia #feliz #so-pt";

$msg = new Mensagem($mensagem);

var_dump($msg);

//Retorna:

object(Mensagem)#1 (2) {
  ["mensagem":protected]=>
  string(35) "Partiu #ferias #praia #feliz #so-pt"
  ["tags":protected]=>
  array(4) {
    [0]=>
    string(6) "ferias"
    [1]=>
    string(5) "praia"
    [2]=>
    string(5) "feliz"
    [3]=>
    string(5) "so"
  }
}

For the search use the following SELECT :

SELECT mensagem FROM mensagens
JOIN mensagens_tags ON mensagens_id_mensagem = id_mensagem
JOIN tags ON tags_id_tag = id_tag
WHERE nome = 'tag';

Sample bank on sqlfiddle .

The next steps are to build the routine that will persist the tags in the database (insert the new tags and keep the old tags) and the system to search. This I leave with you.

    
28.05.2015 / 13:24