Insert string in path

I have a line like this

folder1/folder2/folder3/13007805372971.jpg

What should I do to add a line before the file name? I would like to look like this

folder1/folder2/folder3/sometext_13007805372971.jpg
+3
source share
6 answers

You can use the pathinfo function , which is designed to analyze paths.

$s='folder1/folder2/folder3/13007805372971.jpg';
$x='sometext_';
$fos=pathinfo($s);

$s2=$fos['dirname'].DIRECTORY_SEPARATOR.$x.$fos['basename'];
+8
source

You can use the SplFileInfo class

$file = new SplFileInfo('folder1/folder2/folder3/13007805372971.jpg');
printf('%s/sometext_%s', $file->getPath(), $file->getBasename());

You can also use a constant DIRECTORY_SEPARATORinstead of hard coding a slash in a call.

Live demo

+5
source

, .

$string           = 'folder1/folder2/folder3/13007805372971.jpg';
$last_slash_pos   = strrpos($string, '/');
$path             = substr($string, 0, $last_slash_pos + 1);
$filename         = substr($string, $last_slash_pos + 1);

$filename_prefix  = 'sometext_';
$new_filename     = $path . $filename_prefix . $filename;

echo $new_filename; // Output: folder1/folder2/folder3/sometext_13007805372971.jpg


+3
$filePath = 'folder1/folder2/folder3/13007805372971.jpg';
$str = 'sometext_';

$newPath = dirname($filePath) . DIRECTORY_SEPARATOR . $str . basename($filePath);
+3

preg_replace("/\/([^\/]+)$/", "/sometext_\\1", "folder1/folder2/folder3/13007805372971.jpg");

sometext_ .

0

pathinfo, .

$path_parts =pathinfo($string);
$string = $path_parts['dirname'].'/sometext_'.$path_parts['basename'];
0

All Articles