Know if a word is found in a string in php

3

I have the following code:

$msg = 'Hola :1: quetal??, :2:';
$emoticones = array(':1:',':2:',':3:');
$cntidademoticon = explode(' ', $msg);
foreach ($cntidademoticon as $string) {
    echo '<br>'.$string.'<br>';
}

What I am looking for is to count the quantities of words that match the variable $emoticones .

    
asked by Avancini1 19.08.2018 в 02:46
source

1 answer

4

This can be easily done with the PHP strpos() function. The input data is first the haystack (in your case, the variable $msg ) and the needle (the arrangement), I leave the following example:

<?php 
    $msg = 'Hola :1: quetal??, :2:';
    $emoticones = array(':1:',':2:',':3:');
    $contador = 0;
    $lenght = count($emoticones);
        for ($i = 0; $i < $lenght; $i++){
            if(strpos($msg, $emoticones[$i]) !== false){
                $contador++;
            }
        }
echo "Número de coincidencias: ". $contador;
?>

For the case that we want to know the number of times that the same string is repeated within another, we will use the PHP function substr_count() , it is the same procedure, only now we will create an auxiliary that stores the number of matches and it is added with the accumulator (and if it does not exist, 0 is added, that's why it is important to initialize it at the beginning of the cycle in 0):

<?php 
    $msg = 'Hola :2: quetal??, :2: :1:';
    $emoticones = array(':1:',':2:',':3:');
    $acumulador = 0;
    $aux = 0;
    $lenght = count($emoticones);
        for ($i = 0; $i < $lenght; $i++){
            $aux = 0;
            $aux = substr_count($msg, $emoticones[$i]);
            $acumulador = $acumulador + $aux;
        }
echo "Número de coincidencias: ". $acumulador;
?>

EDIT: It should be noted that the accumulator is only if a array of strings will be used to search within another string

    
answered by 19.08.2018 / 02:59
source