Highlighted searched term in bold with or without accent

2

Hello friends, I would love your help. I'm trying to highlight the words typed in bold in search. the code below works only if you type "Brazilian selection" plus if you type "soccer selection" nothing happens. Thanks in advance for the help .. hugs ..

//$post = "selecao de futebol"; //não funciona
$post = "selecao brasileira"; //funciona

$dados_mysql = "seleção brasileira de futebol";

$post = preg_replace('/[aáàâãäeéèêiíìoóòôõöuúùücç]/','(a|á|à|â|ã|ä|e|é|è|ê|i|í|ì|o|ó|ò|ô|õ|ö|u|ú|ù|ü|c|ç)',$post);
$resultado = preg_replace("/($post?)/i","<b>\0</b>",$dados_mysql);

echo "$resultado";
    
asked by anonymous 04.08.2015 / 03:59

2 answers

5

Do you want to remove accents and leave lowerCase? If it is, the lower () function does this for you. After that, you have to run preg_replace for each word (otherwise it would only match if the two words were followed in both the post and < em> data_mysql ), then you have to do a explode . The findWords () function does this for you.

Do this:

function lower($string) {
    $string = mb_strtolower($string, 'UTF-8');
    $string = preg_replace('/['´^~\'"]/', null, iconv( 'UTF-8', 'ASCII//TRANSLIT', $string ) );
    return $string;
}

function findWords($string1, $string2) {
    $stringLow1 = lower($string1);
    $stringLow2 = lower($string2);

    $stringLow1 = explode(" ", $stringLow1);

    foreach ($stringLow1 as $string) {
        $stringLow2 = preg_replace("/($string?)/i","<b>\0</b>", $stringLow2);
    }

    $string2 = explode(" ", $string2);
    $stringLow2 = explode(" ", $stringLow2);

    foreach ($stringLow2 as $key => $string) {
        if (preg_match("/<b>/", $string)) {
            $string2[$key] = '<b>' . $string2[$key] . '</b>';
        }
    }

    $string2 = implode(" ", $string2);

    return $string2;
}

$dados_mysql = "seleção brasileira de futebol";
$digitado = "seleção de futebol";

echo findWords($digitado, $dados_mysql);

Note: Have you looked into the possibility of doing this on the Front End? This is my suggestion.

    
04.08.2015 / 04:17
2

You can try to develop using the strripos function:

$termo_pesquisa     = 'ababcd';
$buscar             = 'ab';
$pesquisar          = strripos($termo_pesquisa, $buscar);

if ($pesquisar === false) {
    echo "Sinto muito, nós não encontramos ($termo_pesquisa) em ($buscar)";
} else {
    echo "Parabéns!\n";
    echo "Nós encontramos a <strong>($buscar)</strong> em ($termo_pesquisa) na posição ($pesquisar)";
}

If you have questions, you can read the documentation as well: link

    
04.08.2015 / 04:10