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
https://forums.phpfreaks.com/topic/173702-solved-quick-strpossubstr-question/
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);

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.