Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get string piece, before last needle

Given

 $str = "asd/fgh/jkl/123

If we want to get string piece after last slash , we can use function strrchr() right? In php not function, to get string piece, before last slah, that is asd/fgh/jkl ?

I know this can make via regex or other way, I am asking about internal function?

like image 653
ANOTHER Avatar asked Nov 20 '12 10:11

ANOTHER


People also ask

How do you get something before a certain character?

Use the substring() method to get the substring before a specific character, e.g. const before = str. substring(0, str. indexOf('_')); . The substring method will return a new string containing the part of the string before the specified character.

What is Substr in PHP?

substr in PHP is a built-in function used to extract a part of the given string. The function returns the substring specified by the start and length parameter. It is supported by PHP 4 and above.

How to SEARCH end of string in PHP?

The endsWith() function is used to test whether a string ends with the given string or not. This function is case insensitive and it returns boolean value.

How do I get the string after a specific character in PHP?

The strpos() finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.


3 Answers

You can do this by:

explode — Split a string by string (Documentation)

$pieces = explode("/", $str );

example

$str = "asd/fgh/jkl/123";
$pieces = explode("/", $str );
print_r($pieces);

$count= count($pieces);
echo $pieces[$count-1]; //or
echo  end($pieces);

Codepad

like image 197
NullPoiиteя Avatar answered Oct 27 '22 00:10

NullPoiиteя


You can use

$str = "asd/fgh/jkl/123";
echo substr($str, 0,strrpos($str, '/'));

Output

asd/fgh/jkl
like image 45
Baba Avatar answered Oct 26 '22 22:10

Baba


$str = "asd/fgh/jkl/123";

$lastPiece = end(explode("/", $str));

echo $lastPiece;

output: 123;

explode() converts the string into an array using "/" as a separator (you can pick the separator)

end() returns the last item of the array

like image 42
aleation Avatar answered Oct 27 '22 00:10

aleation