Jump to content

Extracting multiple lines after a certain string


mbabli

Recommended Posts

Hello,

  If I have a javascript file with the following:

    var username="test";
    var pagesVisisted=new Array(
      "http://www.yahoo.com",
      "http://www.msn.com",
      "http://www.php.net"
  );
  var lastHit="0608301502";

And I want ONLY the stuff in the pagesVisited Array, how can I do that? Any help would be appreciated.


 
got it,

  $fp = @file(myfile.js);
  for($i=0; $i < count($fp); $i++)
  {
    if(strstr($fp[$i], "visitedPages"))
    {
      while($fp[$i++] != strpos($fp[$i],");"))
      echo "<tr><td>".$fp[$i]."</td></tr>";
    }
}

I still need to strip the " " from around the string, I tried using preg_match("/\"(\w+)\";/", $fp[$i]) with no success. Is there a better way to do this?

[code]
<pre>
<?php

$data = <<<DATA
    var username="test";
    var pagesVisisted=new Array(
      "http://www.yahoo.com",
      "http://www.msn.com",
      "http://www.php.net"
  );
  var lastHit="0608301502";
DATA;

$data_array = explode("\n", $data);

$result = array();
foreach ($data_array as $line) {
if (preg_match('/^\s*"(.+?)"/', $line, $matches)) {
$result[] = $matches[1];
}
}
print_r($result);
?>
</pre>
[/code]
The JS file is user dependent, so, maybe just that or maybe a few thousand lines. + ~10 more variable arrays. My workaround was to simply use str_replace twice, once to filter the first entry and the 2nd to filter the rest of the array entries.


  Here is what I have so far.

<pre>
            $fp = @file('visitedPages.js');
for($i=0; $i < count($fp); $i++)
{
  if(strstr($fp[$i], "visitedPages"))
  {
while($fp[$i++] != strpos($fp[$i],");"))
{
  $result = str_replace('"',' ',$fp[$i]);
  echo "<tr><td><a class=\"linkList\" 
                                  href=\"#\">".str_replace(',',' ',
                                  $result)."</a></td></tr>";
}
  }
}
 
  It does the job for now. But, if there is a better way to do this, I will be in your debt.

Thanks for the followup.


</pre>
I'm not sure it is what you want, but, first of all, I guess is better to use file_get_contents() instead of file().
Try this one :
[CODE]
$js = file_get_contents('visitedPages.js') ;


preg_match('/visitedPages[^\(]+\([^)]+\)/',$js,$mt) ;
preg_match_all('/"([^"]+)"/',$mt[0],$mh) ;

echo '<pre>';
print_r($mh[1]);
[/CODE]
I've used [B]visitedPages[/B] as js array name.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.