How to "undo" any text at the time of "echo" and turn each word into a link

4

I made a database, and in that database I registered a phrase, I would like that when I was to echo the phrase, each word would become a single link. Ex:

recue o código em 4 espaços

The sentence is simple, but I would like each word to create a link. The purpose of this is to improve search engines.

In the example sentence has the word code . If I click on the word code I would like to go to a search page that uses that word.

Using the word is simple, the biggest problem is to break this sentence down and turn each word into a link.

    
asked by anonymous 22.11.2014 / 20:44

3 answers

5

This is a system of tags, usually keywords and not part of a text. They should be individual rather than phrase.

$str = 'recue o código em 4 espaços';
$str = explode( ' ' , $str );

foreach( $str as $palavra )
{
    if( mb_strlen( $palavra ) > 3 )
    echo '<a href="'.$palavra.'">'.$palavra.'</a>';
}

Notice that each word will be a link. I added a check to accept words longer than 3 characters.

Example on ideone

    
22.11.2014 / 20:54
4

In JavaScript:

To break this sentence into the blanks you can do this:

var frase = 'recue o código em 4 espaços';
var palavras = frase.split(' ');
var links = palavras.map(function(palavra) {
    var link = document.createElement('a');
    var casulo = document.createElement('div');
    link.href = '?busca=' + palavra;
    link.innerHTML = palavra;
    casulo.appendChild(link);
    return casulo.innerHTML;
});
document.getElementById('resultado').innerHTML = links.join(' ');
<div id="resultado"></div>

This is a simplified way, could add more checks such as delete short words like ou , a , é etc ...

The variable links will have an array of anchors with the text of the word.

    
22.11.2014 / 20:54
2

And let the games begin! : D

Another approach:

$str = 'recue o código em 4 espaços';

echo implode( ' ',

    array_map(

        function( $word ) {
            return sprintf( '<a href="%1$s">%1$s</a>', $word );
        },

        explode( ' ', $str )
    )
);

If you do not want the words to remain joined by a space the way they were before the replacement, just remove the implode ().

    
22.11.2014 / 21:02