Search code examples
phpstringloopsscreen-scrapingcycle

html scraping and cycling pieces of string


The question is very simple, im doing some html scraping to get bus timelines using php. i have the following string:

Fermata 1179 - Linea 203 -> 13:12 Linea 254 -> 13:19 Linea 203 -> 13:20 Linea 1 -> 13:29

Fermata 1179 is the id of the stop, and its quite easy to get with substr()

what i cant seem to do is cycling through the Lines es:

Linea 203 -> 13:12

Linea 254 -> 13:19

Linea 203 -> 13:20

Linea 1 -> 13:29

i want to display as

Linea 203 at 13:12

Linea 254 at 13:19

Linea 203 at 13:20

Linea 1 at 13:29

what i've done so far ( i know its shit code but i have to start in some way :( )

<?php if ( $scraped_data != 'Previsioni in fermata non disponibili.'){

        // stringa: Fermata 1494 - Linea 202 -> 09:28
        echo 'dati:<br/>'.$scraped_data;    
        $x= 0;


        $idpalina =  substr($scraped_data,8,4); // ID PALINA
        echo '<br />id palina: '.$idpalina;
        echo '<br />posizione di " - ": '.strpos($scraped_data, ' - ');
        echo '<br />';

        // MI PRENDO IL NOME DELLA LINEA
        echo '<br />'.substr($scraped_data,strpos($scraped_data, ' -  ')+2,strpos($scraped_data, ' -> ')-(strpos($scraped_data, ' -  ')+2)); 
        //L ORA DELLA LINEA
        echo '<br />'.substr($scraped_data,strpos($scraped_data, ' -> ')+4,5); 

        // LA POSIZIONE DEL SEPARATORE PER L'ORA
        echo '<br />posizione di " ->": '.strpos($scraped_data, ' -> ');

        // CERCA LA PROSSIMA POSIZIONE DI LINE
        $x= strpos($scraped_data, '->') +9;
        echo  '<br />x= '.$x;
        echo  '<br />strlen= '.strlen($scraped_data);
        echo  '<br />i='.$i;
        // MI PRENDO IL NOME DELLA LINEA
        echo '<br />'.substr($scraped_data,strpos($scraped_data, ' -  ')+$x,strpos($scraped_data, ' -> ')-(strpos($scraped_data, ' -  ')+$x)); 
        echo '<br />'.
        }
        else
        echo 'Previsioni non disponibili';
        ?>

hope someone wil help me as i'm riving mad :(


Solution

  • You can use explode to break up the string as required:

    $string = 'Fermata 1179 - Linea 203 -> 13:12 Linea 254 -> 13:19 Linea 203 -> 13:20 Linea 1 -> 13:29';
    
    $parts = explode('Linea', $string);
    
    //start from 1, as the 1st item in array is 'Fermata 1179 - '
    for($i=1;$i<count($parts);$i++){
        echo '<p>Linea ' . str_replace('->', 'at', $parts[$i]) . '</p>';
    }