Last 4 characters of a filename

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
Indro
New php-forum User
New php-forum User
Posts: 7
Joined: Mon May 07, 2018 5:06 am

Mon May 07, 2018 6:49 am

Hello,

I have several filenames in this format

test_2018.php
test_abc_2017.php
text_def_2016.php

I would like to define $year as the last 4 characters of the file itself, so inside the file, for example in the body of test_2018.php I have the following code:

Code: Select all

$path = getenv('SCRIPT_NAME');
$filename = basename($path, ".php");
$imagename = $filename;
$year = substr($imagename, strrpos($imagename, "2"), 4);
Basically I read the filename, I remove the ".php" and then look for "2" to retrieve the last 4 characters.

This works with all the files ending with 2000 to 201, but not with filenames such as

test_1999.php

How can I modify the code to read the last 4 characters of the filename no matter how long the filename is?

Thanks!
AdoptiveSolution
php-forum Super User
php-forum Super User
Posts: 167
Joined: Wed Jun 15, 2016 8:35 am

Mon May 07, 2018 7:08 am

Code: Select all

$year = substr($imagename, -4);
It's in the manual, example #1

http://php.net/manual/en/function.substr.php
User avatar
hyper
php-forum GURU
php-forum GURU
Posts: 904
Joined: Mon Feb 22, 2016 5:52 pm

Mon May 07, 2018 7:13 am

Use a negative start position

Code: Select all

echo substr('MyString',-4, 2);
You don't need to getenv or any of the other functions.
User avatar
hyper
php-forum GURU
php-forum GURU
Posts: 904
Joined: Mon Feb 22, 2016 5:52 pm

Mon May 07, 2018 7:14 am

Ooops, cross post, same answer :o
Indro
New php-forum User
New php-forum User
Posts: 7
Joined: Mon May 07, 2018 5:06 am

Mon May 07, 2018 7:38 am

Thank you!
Post Reply