Jump to content

[SOLVED] Quick strpos/substr question


Bricktop

Recommended Posts

Hi all,

 

I have numerous files all formatted as follows:

 

$file = 1252439311-backup-file.txt
$file = 8252439314-backup-file.txt
$file = 5252439315-backup-file.txt
$file = 4252439315-backup-file.txt

 

I'm trying to extract the first number string (a UNIX timestamp), before the - and am using the following code but it isn't working.  I'm doing something wrong which I'm sure is really obvious but I can't work it out.

 

The code I'm using is:

 

$i = strrpos($file,'-');
$time = substr($file,$i+1);

 

Thanks in advance.

Link to comment
Share on other sites

strrpos() gives you the last occurrence position of the character, in this case its the - right before file.  You need to use strpos() instead.

 

Once you have the position of the first dash instead of the last one, you can feed it in to substr().

 

Take a look at how to use the function: http://ca.php.net/manual/en/function.substr.php

 

There are a few good examples there, but basically you need to feed in both the start and length parameters, not just the start.

 

So the start will be 0, and the length will be whatever you got from substr().

 

$file = '1252439311-backup-file.txt';
$i = strpos($file,'-');
$time = substr($file, 0, $i);
var_dump($time);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.