Get value from a line using strpos and substr in PHP

Description

The following code shows how to get value from a line using strpos and substr.

Example


/*from   ww w.j a v a  2s  .c  om*/
<?php
   $substr = "index.html";

    $log = <<< logfile
    192.168.1.11:/www/htdocs/index.html:[2010/02/10:20:36:50]
    192.168.1.13:/www/htdocs/about.html:[2010/02/11:04:15:23]
    192.168.1.15:/www/htdocs/index.html:[2010/02/15:17:25]
logfile;

   // what is first occurrence of the time $substr in log?
   $pos = strpos($log, $substr);

   // Find the numerical position of the end of the line
   $pos2 = strpos($log,"\n",$pos);

   // Calculate the beginning of the timestamp
   $pos = $pos + strlen($substr) + 1;

   // Retrieve the timestamp
   $timestamp = substr($log,$pos,$pos2-$pos);

   echo "The file $substr was first accessed on: $timestamp";
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone