Insert automatic link in hashtags

Asked

Viewed 104 times

1

I need a system that identifies the word with # within a text and adds in a table.

And another system that identifies the word with # within a text, however, when it appears in the div, the word is linked.

Example of initial text:

The people at #Stackoverflow are great at #programming.

It turns into:

The staff of #Stackoverflow are great at #programming

1 answer

4


If the target is just the common English accents, it’s easy to list them one by one. I would do a regex with the following blocks:

  • A-Za-z upper and lower case without accent
  • áàâãéèêíïóôõöúçñ: accentuated vowels of Portuguese, cedilla and others of lambuja, lowercase
  • ÁÀÂÃÉÈÊÍÏÓÔÕÖÚÇÑ: accentuated vowels of Portuguese, cedilla and other lambuja vowels, uppercase spaces

Therefore:

/^[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ]+$/

Or, leaving the lowercase/upper case distinction for implementation:

/^[a-záàâãéèêíïóôõöúçñ ]+$/i

So to use with 0-9, a-z, A-Z and accents:

<?php
    $text = "O pessoal do #Stackoverflow são ótimos em #programação.";
    $text = preg_replace('/(?<!\S)#([0-9a-zA-ZáàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ_]+)/', '<a href="http://meusite.com/hashtag/$1">#$1</a>', $text);
    echo $text;
?>
  • Why the space at the end of the regex group?

  • Hey, it worked out! Thanks.

  • @EGDEV The Code has occurred correctly but is with accent error. How do I remove it?

  • Could report the error?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.