Extract filename with extension from filepath string - php

I am looking to get the filename from the end of a filepath string, say
$text = "bob/hello/myfile.zip";
I want to be able to obtain the file name, which I guess would involve getting everything after the last slash as a substring. Can anyone help me with how to do this is PHP? A simple function like:
$fileName = getFileName($text);

Check out basename().

For more general needs, use negative value for start parameter.
For e.g.
<?php
$str = '001234567890';
echo substr($str,-10,4);
?>
will output
1234
Using a negative parameter means that it starts from the start'th character from the end.

$text = "bob/hello/myfile.zip";
$file_name = end(explode("/", $text));
echo $file_name; // myfile.zip
end() returns the last element of a given array.

As Daniel posted, for this application you want to use basename(). For more general needs, strrchr() does exactly what the title of this post asks.
http://us4.php.net/strrchr

I suppose you could use strrpos to find the last '/', then just get that substring:
$fileName = substr( $text, strrpos( $text, '/' )+1 );
Though you'd probably actually want to check to make sure that there's a "/" in there at all, first.

function getSubstringFromEnd(string $string, int $length)
{
return substr($string, strlen($string) - $length, $length);
}
function removeSubstringFromEnd(string $string, int $length)
{
return substr($string, 0, strlen($string) - $length);
}
echo getSubstringFromEnd("My long text", 4); // text
echo removeSubstringFromEnd("My long text", 4); // My long

Related

how to remove the first part of a path in php?

i have a path like this:
/dude/stuff/lol/bruh.jpg
i want to echo it like this:
/stuff/lol/bruh.jpg
how to do this? and if you could please explain it. i found one good answer
Removing part of path in php but i cannot work my way around with explode and implode.
please give me the link to the duplicate answer if my question is a duplicate
You could use strpos with substr:
$string = '/dude/stuff/lol/bruh.jpg';
$string = substr($string, strpos($string, '/', 1));
The strpos to look for the position of the / after the first one, then use substr to get the string starting from that position till the end.
$path = '/dude/stuff/lol/bruh.jpg';
$path = explode('/', $path);
unset($path[1]);
$path = implode('/', $path);
Will separate the string into an array, then unset the first item (technically the second in the array, since the first element will be empty due to the string starting with /). Finally the path is imploded, and you get:
/stuff/lol/bruh.jpg
Try this :
$string = "/dude/stuff/lol/bruh.jpg";
$firstslash = strpos($string,"/",1);
$secondstring = substr($string, $firstslash+1);
echo "String : " . $string;
echo " <br> Result : " . $secondstring;
You can use a regular expression to extract resource name you need.
preg_match('/(?P<name>[^\/]+)$/', $path, $match);
Then you have to use $match as array, and you can see the name inside of it.
$match['name];

Remove all characters after last instance of particular character

How can I remove all the content in a string after the LAST occurance of a slash character / ?
For example, the string is:
http://localhost/new-123-rugby/competition.php?croncode=12345678
I want to remove all the content after the last / so that it just shows:
http://localhost/new-123-rugby/
But the content after the / could be of a variable length.
Please note, there could be any number of slashes in the URL. It needs to be able to remove content after the last slash. There could be more than shown in the example above.
you can try this
$url = "http://localhost/new-123-rugby/competition.php?croncode=12345678";
preg_match("/[^\/]+$/", $url, $matches);
$newUrl = str_replace($matches[0],'',$url);
echo $newUrl;
Solution #1, using substr() + strrpos():
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
$pos = strrpos($string, '/');
if ($pos !== FALSE) {
echo(substr($string, 0, $pos + 1));
}
Function strrpos() finds the position of the last occurrence of / in the string, substr() extracts the required substring.
Drawback: if $string does not contain '/', strrpos() returns FALSE and substr() does not return what we want. Need to check the value returned by strrpos() first.
Solution #2, using explode() + implode():
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
$array = explode('/', $string);
if (count($array) > 1) {
array_pop($array); // ignore the returned value, we don't need it
echo(implode('/', $array).'/'); // join the pieces back, add the last '/'
}
Alternatively, instead of array_pop($array) we can make the last component empty and there is no need to add an extra '/' at the end:
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
$array = explode('/', $string);
if (count($array) > 1) {
$array[count($array) - 1] = ''; // empty the last component
echo(implode('/', $array)); // join the pieces back
}
Drawback (for both versions): if $string does not contain '/', explode() produces an array containing a single value and the rest of the code produces either '/' (the first piece of code) or an empty string (the second). Need to check the number of items in the array produced by explode().
Solution #3, using preg_replace():
$string = 'http://localhost/new-123-rugby/competition.php?croncode=12345678';
echo(preg_replace('#/[^/]*$#', '/', $string));
Drawbacks: none. It works well when both when $string contains '/' and it does not contain '/' (it does not modify $string in this case).
NOTA:
The question was edited so that the original answer (below the edit), doesn't match the requirements from OP. It wasn't marked as an edit from OP.
EDIT:
Updated my answer so it now matches the requirements of OP:
(Now it works with as many slashes as you want)
Will also work using
http://localhost/new-123-rugby////////competition.php?croncode=12345678
<?php
$url = "http://localhost/new-123-rugby/competition.php?croncode=12345678";
echo dirname($url) . "/";
?>
Output:
http://localhost/new-123-rugby/
Original answer:
This should work for you:
<?php
$string = "http://localhost/new-123-rugby/competition.php?croncode=12345678";
echo $string = substr($string, 0, strpos(strrev($string), "/")-2);
?>
Output:
http://localhost/new-123-rugby/
Demo: http://ideone.com/0R9QUG

PHP how do i cut substring after last slash?

Hi i want to know how can i get substring from string after last slash?
In short i want to get the file name from path.
for example i got string like this:
test-e2e4/test-e2e4/test-e2e4/6.png
and i want to get 6.png how can i do that ?
I got dir only and the file name can be all format, it can be also something else then file
Or test-e2e4/test-e2e4/test-e2e4/aaaaa and want to get aaaaa
Regex maybe? Or maybe you know some nice functions which will do it for me ?
In addition to other replies, there's actually a function in PHP to do this: basename. Example:
$string = 'test-e2e4/test-e2e4/test-e2e4/6.png';
$base = basename($string); // $base == '6.png';
$string = 'test-e2e4/test-e2e4/test-e2e4/aaaaa';
$base = basename($string); // $base == 'aaaaa'
$string = '6.png';
$base = basename($string); // $base == '6.png'
Full details here: http://php.net/basename
Do like this..
$yourstring = 'test-e2e4/test-e2e4/test-e2e4/6.png';
$val = array_pop(explode('/',$yourstring)); // 6.png
You can try explode and array_pop functions to work this out:
$str = 'test-e2e4/test-e2e4/test-e2e4/aaaaa.png';
$str = explode('/', $str);
$filename = array_pop($str);
echo $filename; //Output will be aaaaa.png
...Or you can use the following regex:
[^\/]*$
You don't need to use regex for this, you can use substr() to get a portion of the string, and strrpos() to specify which portion:
$full_path = "test-e2e4/test-e2e4/test-e2e4/6.png"
$file = substr( $full_path, strrpos( $full_path, "/" ) + 1 );
substr() returns a portion of the string, strrpos() tells it to start from the position of the last slash in the string, and the +1 excludes the slash from the return value.

How to get everything after a certain character?

I've got a string and I'd like to get everything after a certain value. The string always starts off with a set of numbers and then an underscore. I'd like to get the rest of the string after the underscore. So for example if I have the following strings and what I'd like returned:
"123_String" -> "String"
"233718_This_is_a_string" -> "This_is_a_string"
"83_Another Example" -> "Another Example"
How can I go about doing something like this?
The strpos() finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.
$data = "123_String";
$whatIWant = substr($data, strpos($data, "_") + 1);
echo $whatIWant;
If you also want to check if the underscore character (_) exists in your string before trying to get it, you can use the following:
if (($pos = strpos($data, "_")) !== FALSE) {
$whatIWant = substr($data, $pos+1);
}
strtok is an overlooked function for this sort of thing. It is meant to be quite fast.
$s = '233718_This_is_a_string';
$firstPart = strtok( $s, '_' );
$allTheRest = strtok( '' );
Empty string like this will force the rest of the string to be returned.
NB if there was nothing at all after the '_' you would get a FALSE value for $allTheRest which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.
Here is the method by using explode:
$text = explode('_', '233718_This_is_a_string', 2)[1]; // Returns This_is_a_string
or:
$text = end((explode('_', '233718_This_is_a_string', 2)));
By specifying 2 for the limit parameter in explode(), it returns array with 2 maximum elements separated by the string delimiter. Returning 2nd element ([1]), will give the rest of string.
Here is another one-liner by using strpos (as suggested by #flu):
$needle = '233718_This_is_a_string';
$text = substr($needle, (strpos($needle, '_') ?: -1) + 1); // Returns This_is_a_string
I use strrchr(). For instance to find the extension of a file I use this function:
$string = 'filename.jpg';
$extension = strrchr( $string, '.'); //returns "jpg"
Another simple way, using strchr() or strstr():
$str = '233718_This_is_a_string';
echo ltrim(strstr($str, '_'), '_'); // This_is_a_string
In your case maybe ltrim() alone will suffice:
echo ltrim($str, '0..9_'); // This_is_a_string
But only if the right part of the string (after _) does not start with numbers, otherwise it will also be trimmed.
if anyone needs to extract the first part of the string then can try,
Query:
$s = "This_is_a_string_233718";
$text = $s."_".substr($s, 0, strrpos($s, "_"));
Output:
This_is_a_string
$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"
In a single statement it would be.
echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"
If you want to get everything after certain characters and if those characters are located at the beginning of the string, you can use an easier solution like this:
$value = substr( '123_String', strlen( '123_' ) );
echo $value; // String
Use this line to return the string after the symbol or return the original string if the character does not occur:
$newString = substr($string, (strrpos($string, '_') ?: -1) +1);

PHP substring extraction. Get the string before the first '/' or the whole string

I am trying to extract a substring. I need some help with doing it in PHP.
Here are some sample strings I am working with and the results I need:
home/cat1/subcat2 => home
test/cat2 => test
startpage => startpage
I want to get the string till the first /, but if no / is present, get the whole string.
I tried,
substr($mystring, 0, strpos($mystring, '/'))
I think it says - get the position of / and then get the substring from position 0 to that position.
I don't know how to handle the case where there is no /, without making the statement too big.
Is there a way to handle that case also without making the PHP statement too complex?
The most efficient solution is the strtok function:
strtok($mystring, '/')
NOTE: In case of more than one character to split with the results may not meet your expectations e.g. strtok("somethingtosplit", "to") returns s because it is splitting by any single character from the second argument (in this case o is used).
#friek108 thanks for pointing that out in your comment.
For example:
$mystring = 'home/cat1/subcat2/';
$first = strtok($mystring, '/');
echo $first; // home
and
$mystring = 'home';
$first = strtok($mystring, '/');
echo $first; // home
Use explode()
$arr = explode("/", $string, 2);
$first = $arr[0];
In this case, I'm using the limit parameter to explode so that php won't scan the string any more than what's needed.
$first = explode("/", $string)[0];
What about this :
substr($mystring.'/', 0, strpos($mystring, '/'))
Simply add a '/' to the end of mystring so you can be sure there is at least one ;)
Late is better than never. php has a predefined function for that. here is that good way.
strstr
if you want to get the part before match just set before_needle (3rd parameter) to true
http://php.net/manual/en/function.strstr.php
function not_strtok($string, $delimiter)
{
$buffer = strstr($string, $delimiter, true);
if (false === $buffer) {
return $string;
}
return $buffer;
}
var_dump(
not_strtok('st/art/page', '/')
);
One-line version of the accepted answer:
$out=explode("/", $mystring, 2)[0];
Should work in php 5.4+
This is probably the shortest example that came to my mind:
list($first) = explode("/", $mystring);
1) list() will automatically assign string until "/" if delimiter is found
2) if delimiter "/"is not found then the whole string will be assigned
...and if you get really obsessed with performance, you may add extra parameter to explode explode("/", $mystring, 2) which limits maximum of the returned elements.
The function strstr() in PHP 5.3 should do this job.. The third parameter however should be set to true..
But if you're not using 5.3, then the function below should work accurately:
function strbstr( $str, $char, $start=0 ){
if ( isset($str[ $start ]) && $str[$start]!=$char ){
return $str[$start].strbstr( $str, $char, $start+1 );
}
}
I haven't tested it though, but this should work just fine.. And it's pretty fast as well
You can try using a regex like this:
$s = preg_replace('|/.*$|', '', $s);
sometimes, regex are slower though, so if performance is an issue, make sure to benchmark this properly and use an other alternative with substrings if it's more suitable for you.
Using current on explode would ease the process.
$str = current(explode("/", $str, 2));
You could create a helper function to take care of that:
/**
* Return string before needle if it exists.
*
* #param string $str
* #param mixed $needle
* #return string
*/
function str_before($str, $needle)
{
$pos = strpos($str, $needle);
return ($pos !== false) ? substr($str, 0, $pos) : $str;
}
Here's a use case:
$sing = 'My name is Luka. I live on the second floor.';
echo str_before($sing, '.'); // My name is Luka
$arr = explode("/", $string, 2); $first = $arr[0];
This Way is better and more accurate than strtok
because if you wanna get the values before # for example
while the there's no string before # it will give you whats after the sign .
but explode doesnt
$string="kalion/home/public_html";
$newstring=( stristr($string,"/")==FALSE ) ? $string : substr($string,0,stripos($string,"/"));
why not use:
function getwhatiwant($s)
{
$delimiter='/';
$x=strstr($s,$delimiter,true);
return ($x?$x:$s);
}
OR:
function getwhatiwant($s)
{
$delimiter='/';
$t=explode($delimiter, $s);
return ($t[1]?$t[0]:$s);
}

Categories