0

I have a problem with the code below which is driving me crazy. What I want to do is to compare a given array with a sentence and then I need to know their position in the sentence for each occurrence, by now the script only return just one array, for example with the positions in which the name Marta is found inside the sentence. I trying to merge all the results in just one array but I'm a bit lost at the moment. I hope someone can give me some clues to make it. Best regards.

$sentence = 'Maria is Maria and Marta is Marta.';
$womennames = array("Maria","Marta");    

function poswomen($chain, $words){

    foreach($words as $findme){
        $valida_existe = substr_count($chain,$findme);
        $largo_encuentra = strlen($findme);
        $posicion = array();

        for($x=0; $x < strlen($chain); $x++){
            $posic_x = strpos($chain, $findme, $x);
            if($posic_x >= 0){              
                $posicion[] = $posic_x;                    
                $x = $x+$largo_encuentra;
            }            
        }

        $posicion = array_unique($posicion);        
        $posicion = implode(",",$posicion);   

    }
    return $posicion;
}

poswomen($sentence, $womennames); 
print_r (poswomen($sentence, $womennames));
3
  • 2
    You're resetting $posicion each at the beginning of each iteration of the foreach array. You should initialize it outside the loop. Commented Jun 9, 2014 at 5:22
  • Thanks Barmar, I was not understanding the work flow of the bucle. Commented Jun 9, 2014 at 15:17
  • Sorry I mean loop, 'bucle' is in Spanish... Commented Jun 9, 2014 at 17:53

1 Answer 1

1

Just like barmar has said, your position keeps resetting you need to set it outside, from that , then add the currently found position so that it will carry on. Consider this example:

$sentence = 'Maria is Maria and Marta is Marta.';
$women_names = array('Maria', 'Marta');
$pos = 0;
$positions = array();

foreach($women_names as $name) {
    while (($pos = strpos($sentence, $name, $pos))!== false) {
        $positions[$name][] = $pos;
        $pos += strlen($name);
    }
    $positions[$name] = implode(', ', $positions[$name]);
}

echo '<pre>';
print_r($positions);
echo '</pre>';

Sample Output:

Array
(
    [Maria] => 0, 9
    [Marta] => 19, 28
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you very much Kevinabelita, I really appreciate your help, it works perfectly ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.