PHP RegEx extract filename - php

I need your help with a RegEx in PHP
I have something like:
vacation.jpg and I am looking for a RegEx which extracts me only the 'vacation' of the filename.
Can someone help me?

Don't use a regex for this - use basename:
$fileName = basename($fullname, ".jpg");

You can use pathinfo instead of Regex.
$file = 'vacation.jpg';
$path_parts = pathinfo($file);
$filename = $path_parts['filename'];
echo $filename;

And if you really need regex, this one will do it:
$success = preg_match('~([\w\d-_]+)\.[\w\d]{1,4}~i', $original_string, $matches);
Inside matches you will have first part of file name.

Better answers have already been provided, but here's another alternative!
$fileName = "myfile.jpg";
$name = str_replace(substr($fileName, strpos($fileName,".")), "", $fileName);

You don't need regex for this.
Approach 1:
$str = 'vacation.jpg';
$parts = explode('.', basename($str));
if (count($parts) > 1) array_pop($parts);
$filename = implode('.', $parts);
Approach 2 (better, use pathinfo()):
$str = 'vacation.jpg';
$filename = pathinfo($str, PATHINFO_FILENAME);

Related

How to remove part of a string with php?

Hello guys so I have a string where the begin part is the same
the string looks like this where the begin part is always ../images/
$img = "../images/image2.jpg";
but the image2.jpg can be something like image_23423.png
how can I remove the ../images/ part?
I tought about str_replace but Could not get it to work
Thanks in advance
The basename() would be helpful for you.
<?php
$img = "../images/image2.jpg";
$img = basename($img); //holds just `image2.jpg`
You could use PHP explode to separate the strings
http://www.php.net/explode
http://php.net/array_pop
$img = "../images/image2.jpg";
$parts = explode('/', $img);
$img = array_pop($parts);
There are different ways:
basename:
$img = "../images/image2.jpg";
$img = basename($img);
explode and end:
$img = "../images/image2.jpg";
$parts = explode('/', $img);
$img = end($parts); // takes the last element in $parts
explode and array_pop:
$img = "../images/image2.jpg";
$parts = explode('/', $img);
$img = array_pop($parts); // takes the last element in $parts and removes it
str_replace:
$img = "../images/image2.jpg";
$img = str_replace('../images/', '', $img);
There are more ways to do this, but those are the most important ones.
This should work:
$img = str_replace('../images/', '', $img);
$imgout = str_replace("../images/", '', $img);
or use explode()
$imgout = explode('/', $img);
$imgname = $imgout[2];
pathinfo() will suitably extract the information you need from the string. See http://uk3.php.net/pathinfo
$img = "../images/image2.jpg";
$imgDetails = pathinfo($img);
$imgName = $imgDetails['basename'];
print_r($imgDetails); // Will show you what other formats you can get the filename in, including extension etc.
basename() is also exposed as a function which you could use
Try this:
PHP
$path = "../images/image2.jpg";
$path_arr = explode("/", $path);
echo $path_arr[0]; // ..
echo $path_arr[1]; // images
echo $path_arr[2]; // image2.jpg
You can do this
$subject = 'REGISTER 11223344 here';
$search = '11223344'
$trimmed = str_replace($search, '', $subject);
echo $trimmed

PHP: Crop file/directory path

I have a long path like this - /home/user/www/domain.net/public_html/system/dir/file.php, and I want crop this to get something like - /system/dir/file.php.
Now I am using this code:
$filename = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $filename);
$filename = join(DIRECTORY_SEPARATOR, array_slice(explode(DIRECTORY_SEPARATOR, $filename), -3, 3));
And it works, but I think there is a better solution.. Anyone know?
Thanks in advance.
You can use regex instead. See this sample:
$sFileName = '/home/user/www/domain.net/public_html/system/dir/file.php';
$iCropCount = 3;
$sResult = preg_replace('#.*?((\/[^\/]+){'.$iCropCount.'})$#', '$1', $sFileName));
//var_dump($sResult);
Operations with DIRECTORY_SEPARATOR are omitted (since main sense of sample above are not in them)
I think you only need the web directory. So you can explode with /public_html as it is always going to be there.
E.g :
$filename = '/home/user/www/domain.net/public_html/system/dir/file.php';
$path = explode('/public_html', $filename);
echo $path[1];
I found other solution:
$filename = '/home/user/www/domain.net/public_html/system/dir/file.php';
explode($_SERVER['DOCUMENT_ROOT'], $filename);
$filename = end($filename);

Get the file extension [duplicate]

This question already has answers here:
How to get a file's extension in PHP?
(31 answers)
Closed 2 years ago.
I'm exploding on "." to get file format and name:
list($txt, $ext) = explode(".", $name);
The problem is that some files have names with dots.
How do I explote on the LAST "." so that I get $name=pic.n2 and $ext=jpg from: pic.n2.jpg?
Use pathinfo:
$pi = pathinfo($name);
$txt = $pi['filename'];
$ext = $pi['extension'];
$name = pathinfo($file, PATHINFO_FILENAME);
$ext = pathinfo($file, PATHINFO_EXTENSION);
http://www.php.net/pathinfo
use this
$array = explode(".", $name);
end($array); // move the internal pointer to the end of the array
$filetype = current($array);
thanks
Use Pathinfo or mime_content_type to get file type information
$filetype = pathinfo($file, PATHINFO_FILENAME);
$mimetype = mime_content_type($file);
Use PHP's pathinfo() function.
See more information here http://php.net/manual/en/function.pathinfo.php
$file_part = pathinfo('123.test.php');
Example:
echo $file_part['extension'];
echo $file_part['filename'];
Output:
php
123.test
<?php
$path = 'http://www.mytest.com/public/images/portfolio/i-vis/abc.y1.jpg';
echo $path."<br/>";
$name = basename($path);
$dir = dirname($path);
echo $name."<br/>";
echo $dir."<br/>";
$pi = pathinfo($path);
$txt = $pi['filename']."_trans";
$ext = $pi['extension'];
echo $dir."/".$txt.".".$ext;
?>
you can write your own function as
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
You might try something like this:
<?php
$file = 'a.cool.picture.jpg';
$ext = substr($file, strrpos($file, '.')+1, strlen($file)-strrpos($file, '.'));
$name = substr($file, 0, strrpos($file, '.'));
echo $name.'.'.$ext;
?>
The key functions are strrpos() which finds the last occurrence of a character (a "." in this case) and substr() which returns a sub string. You find the last "." in the file, and sub string it. Hope that helps.
It is better to use one of the solutions above, but there is also a solution using the explode function:
$filename = "some.file.name.ext";
list($ext, $name) = explode(".", strrev($filename), 2);
$name = strrev($name);
$ext = strrev($ext);
What this solution does is the following:
1. reverse string, so it will look like: txe.eman.elif.emos
2. explode it, you will get something like: $ext = "txe", $name = "eman.elif.emos"
3. reverse each of the variables to get the correct results

PHP strip unknown file extension

I understand that using PHP's basename() function you can strip a known file extension from a path like so,
basename('path/to/file.php','.php')
but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?
Thanks in advance!
pathinfo() was already mentioned here, but I'd like to add that from PHP 5.2 it also has a simple way to access the filename WITHOUT the extension.
$filename = pathinfo('path/to/file.php', PATHINFO_FILENAME);
The value of $filename will be file.
You can extract the extension using pathinfo and cut it off.
// $filepath = '/path/to/some/file.txt';
$ext = pathinfo($filepath, PATHINFO_EXTENSION);
$basename = basename($filepath, ".$ext");
Note the . before $ext
$filename = preg_replace('#\.([^\.]+)$#', '', $filename);
You can try with this:
$filepath = 'path/to/file.extension';
$extension = strtolower(substr(strrchr($filepath, '.'), 1));
Try this:-
$path = 'path/to/file.php';
$pathParts = pathinfo( $path );
$pathWihoutExt = $pathParts['dirname'] . DIRECTORY_SEPARATOR . $pathParts['filename'];

How can I change a file's extension using PHP?

How can I change a file's extension using PHP?
Ex: photo.jpg to photo.exe
In modern operating systems, filenames very well might contain periods long before the file extension, for instance:
my.file.name.jpg
PHP provides a way to find the filename without the extension that takes this into account, then just add the new extension:
function replace_extension($filename, $new_extension) {
$info = pathinfo($filename);
return $info['filename'] . '.' . $new_extension;
}
substr_replace($file , 'png', strrpos($file , '.') +1)
Will change any extension to what you want. Replace png with what ever your desired extension would be.
Replace extension, keep path information
function replace_extension($filename, $new_extension) {
$info = pathinfo($filename);
return ($info['dirname'] ? $info['dirname'] . DIRECTORY_SEPARATOR : '')
. $info['filename']
. '.'
. $new_extension;
}
You may use the rename(string $from, string $to, ?resource $context = null) function.
Once you have the filename in a string, first use regex to replace the extension with an extension of your choice. Here's a small function that'll do that:
function replace_extension($filename, $new_extension) {
return preg_replace('/\..+$/', '.' . $new_extension, $filename);
}
Then use the rename() function to rename the file with the new filename.
Just replace it with regexp:
$filename = preg_replace('"\.bmp$"', '.jpg', $filename);
You can also extend this code to remove other image extensions, not just bmp:
$filename = preg_replace('"\.(bmp|gif)$"', '.jpg', $filename);
For regex fans,
modified version of Thanh Trung's 'preg_replace' solution that will always contain the new extension (so that if you write a file conversion program, you won't accidentally overwrite the source file with the result) would be:
preg_replace('/\.[^.]+$/', '.', $file) . $extension
Better way:
substr($filename, 0, -strlen(pathinfo($filename, PATHINFO_EXTENSION))).$new_extension
Changes made only on extension part. Leaves other info unchanged.
It's safe.
You could use basename():
$oldname = 'path/photo.jpg';
$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, 'jpg') . 'exe';
Or for all extensions:
$newname = (dirname($oldname) ? dirname($oldname) . DIRECTORY_SEPARATOR : '') . basename($oldname, pathinfo($path, PATHINFO_EXTENSION)) . 'exe';
Finally use rename():
rename($oldname, $newname);
Many good answers have been suggested. I thought it would be helpful to evaluate and compare their performance. Here are the results:
answer by Tony Maro (pathinfo) took 0.000031040740966797 seconds. Note: It has the drawback for not including full path.
answer by Matt (substr_replace) took 0.000010013580322266 seconds.
answer by Jeremy Ruten (preg_replace) took 0.00070095062255859 seconds.
Therefore, I would suggest substr_replace, since it's simpler and faster than others.
Just as a note, There is the following solution too which took 0.000014066696166992 seconds. Still couldn't beat substr_replace:
$parts = explode('.', $inpath);
$parts[count( $parts ) - 1] = 'exe';
$outpath = implode('.', $parts);
I like the strrpos() approach because it is very fast and straightforward — however, you must first check to ensure that the filename has any extension at all. Here's a function that is extremely performant and will replace an existing extension or add a new one if none exists:
function replace_extension($filename, $extension) {
if (($pos = strrpos($filename , '.')) !== false) {
$filename = substr($filename, 0, $pos);
}
return $filename . '.' . $extension;
}
I needed this to change all images extensions withing a gallery to lowercase. I ended up doing the following:
// Converts image file extensions to all lowercase
$currentdir = opendir($gallerydir);
while(false !== ($file = readdir($currentdir))) {
if(strpos($file,'.JPG',1) || strpos($file,'.GIF',1) || strpos($file,'.PNG',1)) {
$srcfile = "$gallerydir/$file";
$filearray = explode(".",$file);
$count = count($filearray);
$pos = $count - 1;
$filearray[$pos] = strtolower($filearray[$pos]);
$file = implode(".",$filearray);
$dstfile = "$gallerydir/$file";
rename($srcfile,$dstfile);
}
}
This worked for my purposes.

Categories