Get the string part, before the last needle

Considering

$str = "asd/fgh/jkl/123 

If we want to get the string after the last slash, we can use the strrchr() function correctly? In php not function, to get the line, to the last slah, i.e. asd/fgh/jkl ?

I know this can be done with a regex or in another way, I ask about an internal function?

+4
source share
4 answers

you can use

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

Output

 asd/fgh/jkl 
+14
source
 $str = "asd/fgh/jkl/123"; $lastPiece = end(explode("/", $str)); echo $lastPiece; 

output: 123;

explode () converts a string to an array using "/" as a separator (you can choose a separator)

end () returns the last element of the array

+1
source

You can do it:

explode - Split 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

0
source

Use this powerful custom feature.

  /* $position = false and $sub = false show result of before first occurance of $needle */ /* $position = true and $sub false show result of before last occurance of $needle */ /* $position = false and $sub = true show result of after first occurance of $needle */ /* $position = true and $sub true show result of after last occurance of $needle */ function CustomStrStr($str,$needle,$position = false,$sub = false) { $Isneedle = strpos($str,$needle); if ($Isneedle === false) return false; $needlePos =0; $return; if ( $position === false ) $needlePos = strpos($str,$needle); else $needlePos = strrpos($str,$needle); if ($sub === false) $return = substr($str,0,$needlePos); else $return = substr($str,$needlePos+strlen($needle)); return $return; } 
0
source

Source: https://habr.com/ru/post/1447192/


All Articles