TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Gah.. Regex? (http://www.talkphp.com/general/3291-gah-regex.html)

Gareth 08-26-2008 08:57 PM

Gah.. Regex?
 
Hi,

If i have a file named something (123).jpg, where 123 is an integer, is there a way where I can get the integer to use in the rest of my script?

I think its regex- not sure though.

Thanks for any help :)

delayedinsanity 08-27-2008 12:04 AM

There's a few ways.

basename and explode come to mind.

PHP Code:

$file '/path/to/file/filename.ext';
$file_name basename($file); // returns "filename"

$file 'filename.ext';
$file_arr explode('.'$file);
echo 
$file_arr[0]; // returns "filename" 


Wildhoney 08-27-2008 12:05 AM

php Code:
$file = '/path/to/file/filename.ext';
$file_name = pathinfo($file, PATHINFO_FILENAME); // returns "filename"
 

php Code:
$pFile = (object) pathinfo('/path/to/file/filename.ext');

printf("Directory: %s<br />\n", $pFile->dirname);
printf("Base: %s<br />\n", $pFile->basename);
printf("Extension: %s<br />\n", $pFile->extension);
printf("Filename: %s<br />\n", $pFile->filename);

Gareth 08-27-2008 12:18 AM

Thanks, but the problem is I only need part of the filename, specifically the part between the () (but not including them)...

Wildhoney 08-27-2008 12:22 AM

php Code:
$pFile = (object) pathinfo('/path/to/file/(123).jpg');
printf("Filename: %s", preg_replace('~[^\d]~i', '', $pFile->filename));

Gareth 08-27-2008 12:51 AM

I love you wildhoney- could you explain or point me in the right direction the preg_replace you gave me? Its greek to me (although funnily enough i did actually study greek...)...!

delayedinsanity 08-27-2008 12:54 AM

Oh, your file is named 'something(123).jpg' not '123.jpg'.

I misunderstood.
-m

Gareth 08-27-2008 01:00 AM

Its my fault, i should have made myself clearer :)

Wildhoney 08-27-2008 01:49 AM

All it means is anything that's not an integer (^\d -- ^ being not, and \d meaning digit) should be replaced with null.

Gareth 08-27-2008 11:58 AM

Ahh, too easy! Thanks.


All times are GMT. The time now is 06:04 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0