Find the matches of a string in an Array

0

I have this code where I define an array and then there is a String, I want to find the matches for each possible value of the array, in this example I would have to return 2 matches in the string $ searchname but the print_r that I do returns an array empty.

$arrayPacs = array('PAC1','PAC2','PAC3');
$nombreBuscar = 'esto es una prueba de PAC1 sobre la PAC1';

print_r(array_keys($arrayPacs,$nombreBuscar));
    
asked by edica 30.08.2018 в 14:47
source

2 answers

0

You could try this:

$arrayPacs = array('PAC1','PAC2','PAC3');
$nombreBuscar = 'esto es una prueba de PAC1 sobre la PAC1';

$arr = array();

for($i = 0; $i < count($arrayPacs); $i++ )
{
    $text = "/".$arrayPacs[$i]."+/i"; //Expresion regular para buscar coincidencias
    preg_match_all($text, $nombreBuscar, $match);
    if(empty(!$match[0]))
    {
        $arr[$arrayPacs[$i]] = count($match[0]);//Array con numero de coincidencias
        echo "<pre>";
        print_r($match[0]);//Se imprime el array que contiene las coincidencias
        echo "Num de coincidencias :".count($match[0]);
        echo "</pre>";
    }
    else
    {
        $arr[$arrayPacs[$i]] = 0;
    }
}
print_r($arr);//Se imprime el array con el numero de coincidencias
    
answered by 30.08.2018 / 16:59
source
2

I understand that you want to get something like this:

Array
(
    [PAC1] => 2
    [PAC2] => 0
    [PAC3] => 0
)

You could use array_map to apply the same function to each position of your $arrayPacs and in this function use substr_count to count the number of occurrences of each position of the array in your string:

$arrayPacs = array('PAC1','PAC2','PAC3');
$nombreBuscar = 'esto es una prueba de PAC1 sobre la PAC1';

$map = array_map(function($key) use ($nombreBuscar) {
    return substr_count($nombreBuscar, $key);
}, $arrayPacs);
$arrayPacs = array_combine($arrayPacs, $map); // Para mantener las keys de tu $arrayPacs
print_r($arrayPacs);

UPDATE

I update according to the comment of @ Sr1871, more correct with use , but I point out how it works use vs global translated from an answer from OS in English:

$global_variable = 1;

$closure = function() use ($global_variable) {
    return $global_variable; 
};

$closure2 = function() {
    global $global_variable;
    return $global_variable;
};

$global_variable = 99;

echo $closure();    // Esto mostraría 1
echo $closure2();   // Esto mostraría 99

use takes the value of $global_variable at the time of defining the function (closure) while global takes the current value of $global_variable at the time of execution.

global inherits variables from the global scope, while use inherits them from its local scope.

If we used ... use (&$global_variable) we would get the same result as with global .

    
answered by 30.08.2018 в 15:10