strrchr

(PHP 4, PHP 5)

strrchrНаходит последнее вхождение символа в строке

Описание

string strrchr ( string $haystack , mixed $needle )

Возвращает подстроку строки haystack начиная с последнего вхождения needle до конца строки.

Список параметров

haystack

Строка, в которой производится поиск

needle

Если needle состоит более чем из одного символа, используется только первый символ. Это поведение отличается от strstr().

Если needle не является строкой, он приводится к целому и трактуется как код символа.

Возвращаемые значения

Функция возвращает фрагмент строки, или FALSE, если подстрока needle не найдена.

Список изменений

Версия Описание
4.3.0 Эта функция теперь бинарно-безопасна.

Примеры

Пример #1 Пример использования strrchr()

<?php
// получить последнюю директорию из $PATH
$dir substr(strrchr($PATH":"), 1);

// получить все после последнего перевода строки
$text "Line 1\nLine 2\nLine 3";
$last substr(strrchr($text10), );
?>

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Смотрите также

  • strstr() - Находит первое вхождение подстроки
  • strrpos() - Возвращает позицию последнего вхождения подстроки в строке

Коментарии

this functions returns the name of the current directory.
<?php
function currentd() {
    return 
substr(strrchr(`pwd`, '/'), 1);
}
?>
2002-11-16 17:02:18
http://php5.kiev.ua/manual/ru/function.strrchr.html
<?

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

   
// Returns everything before $needle (inclusive).
   
return substr($haystack,0,strpos($haystack,$needle)+1);
   
}

$string "FIELD NUMBER(9) NOT NULL";

echo 
strrrchr($string,")"); // Will print FIELD (9)

?>
2003-04-14 15:43:48
http://php5.kiev.ua/manual/ru/function.strrchr.html
strrchr is also very useful for finding the extension of a file. For example:

$ext = strrchr($filename, ".");

and $ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "evilfile.jpg.vbs", then this construction will just return the last extension.
2003-05-23 19:24:48
http://php5.kiev.ua/manual/ru/function.strrchr.html
The function provided by marcokonopacki at hotmail dot com isn't really a reverse-version of strrchr(), rather a reverse version of strchr(). It returns everything from the start of $haystack up to the FIRST instance of the $needle. This is basically a reverse of the behavior which you expect from strchr(). A reverse version of strrchr() would return everything in $haystack up to the LAST instance of $needle, eg:

<?php
// reverse strrchr() - PHP v4.0b3 and above
function reverse_strrchr($haystack$needle)
{
   
$pos strrpos($haystack$needle);
    if(
$pos === false) {
        return 
$haystack;
    }
    return 
substr($haystack0$pos 1);
}
?>

Note that this function will need to be modified slightly to work with pre 4.0b3 versions of PHP due to the return type of strrpos() ('0' is not necessarily 'false'). Check the documentation on strrpos() for more info. 

A function like this can be useful for extracting the path to a script, for example:

<?
$string 
"/path/to/the/file/filename.php";

echo 
reverse_strrchr($string'/'); // will echo "/path/to/the/file/"
?>
2004-02-16 21:16:20
http://php5.kiev.ua/manual/ru/function.strrchr.html
I used dchris1 at bigpond dot net dot au 's reverse strrchr and reduced it to one line of code and fixed it's functionality - the real strrchr() returns FALSE if the needle is not found, not the haystack :)

<?php
// reverse strrchr()
function reverse_strrchr($haystack$needle)
{
                return 
strrpos($haystack$needle) ? substr($haystack0strrpos($haystack$needle) +) : false;

?>
2005-04-03 14:45:03
http://php5.kiev.ua/manual/ru/function.strrchr.html
$filename = 'strrchr_test.php';
print strrchr( $filename, '.' );

Result:
.php

$other_filename = 'strrchr_test.asp.php';
print  strrchr( $other_filename, '.' );

Result:
.php
2005-07-29 13:24:18
http://php5.kiev.ua/manual/ru/function.strrchr.html
A quick way to get file's extension (if it has one, otherwise you get an empty string), which can be used when you want to rename the file but keep the old extension. Or for similar purposes. Temporary variable is used just because it's slightly faster to store the value than to run the strrchr() function again.

<?php
$ext 
substr(($t=strrchr("file.ext",'.'))!==false?$t:'',1);
?>
2005-11-11 08:26:38
http://php5.kiev.ua/manual/ru/function.strrchr.html
to marcokonopacki at hotmail dot com.

I had to make a slight change in your function for it to return the complete needle inclusive.

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

   // Returns everything before $needle (inclusive).
   //return substr($haystack,0,strpos($haystack,$needle)+1);
   // becomes
   return substr($haystack,0,strpos($haystack,$needle)+strlen($needle));
}

Note: the +1 becomes +strlen($needle)

Otherwise it only returns the first character in needle backwards.
2005-12-25 00:54:06
http://php5.kiev.ua/manual/ru/function.strrchr.html
just a small addition to carlos dot lage at gmail dot com note which makes it a bit more useful and flexible:

<?php
// return everything up to last instance of needle
// use $trail to include needle chars including and past last needle 
function reverse_strrchr($haystack$needle$trail) {
    return 
strrpos($haystack$needle) ? substr($haystack0strrpos($haystack$needle) + $trail) : false;
}
// usage:
$ns = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/"0));
$ns2 = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/"1));
echo(
$ns "<br>" $ns2);
?>
2006-04-08 20:43:23
http://php5.kiev.ua/manual/ru/function.strrchr.html
Get file name and extension into an array with or without dot, using strrchr and strrchr_reverse.

<?
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack$needle$l_inclusive 0$r_inclusive 0){
   if(
strrpos($haystack$needle)){
       
//Everything before last $needle in $haystack.
       
$left substr($haystack0strrpos($haystack$needle) + $l_inclusive);
 
       
//Switch value of $r_inclusive from 0 to 1 and viceversa.
       
$r_inclusive = ($r_inclusive == 0) ? 0;
 
       
//Everything after last $needle in $haystack.
       
$right substr(strrchr($haystack$needle), $r_inclusive);
 
       
//Return $left and $right into an array.
       
$a = array($left$right);
       return 
$a;
   }else{
       return 
false;
   }
}

//start test
$haystack "unknown.txt.log.......gif.....jpeg";
$needle ".";
$l_inclusive 1//1 for inclusive mode, 0 for NOT inclusive mode
$r_inclusive 1//1 for inclusive mode, 0 for NOT inclusive mode

$a strxchr($haystack$needle$l_inclusive$r_inclusive);
if(
$a){echo "Left: <strong>" $a[0] . "</strong><br /> Right: <strong>" $a[1] . "</strong>";}else{echo "Failed!";}
//end test
?>

Thanks to all.

Repley
2006-05-18 18:09:19
http://php5.kiev.ua/manual/ru/function.strrchr.html
to: repley at freemail dot it

the code works very well, but as i was trying to cut script names (e.g.: $_SERVER["SCRIPT_NAME"] => /index.php, cut the string at "/" and return "index.php") it returned nothing (false). i've modified your code and now it works also if the needle is the first char.
- regards from germany

<?php
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack$needle$l_inclusive 0$r_inclusive 0){
   if(
strrpos($haystack$needle)){
       
//Everything before last $needle in $haystack.
       
$left substr($haystack0strrpos($haystack$needle) + $l_inclusive);
 
       
//Switch value of $r_inclusive from 0 to 1 and viceversa.
       
$r_inclusive = ($r_inclusive == 0) ? 0;
 
       
//Everything after last $needle in $haystack.
       
$right substr(strrchr($haystack$needle), $r_inclusive);
 
       
//Return $left and $right into an array.
       
return array($left$right);
   } else {
       if(
strrchr($haystack$needle)) return array(''substr(strrchr($haystack$needle), $r_inclusive));
       else return 
false;
   }
}
?>
2006-06-06 22:55:42
http://php5.kiev.ua/manual/ru/function.strrchr.html
Final get file name and extension into an array with or without dot, using strrchr and strrchr_reverse.
Note our use of !==. Now work if the position of $needle in $haystack was the 0th (first) character like ".htaccess"
<?
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack$needle$l_inclusive 0$r_inclusive 0){
   
//Note our use of !==. Now work if the position of $needle in $haystack was the 0th (first) character.
   
if(strrpos($haystack$needle) !== false){
       
//Everything before last $needle in $haystack.
       
$left substr($haystack0strrpos($haystack$needle) + $l_inclusive);
       
//Switch value of $r_inclusive from 0 to 1 and viceversa.
       
$r_inclusive = ($r_inclusive == 0) ? 0;
       
//Everything after last $needle in $haystack.
       
$right substr(strrchr($haystack$needle), $r_inclusive);
       
//Return $left and $right into an array.
       
$a = array($left$right);
       return 
$a;
   }else{
       return 
false;
   }
}
?>

Repley
2006-08-11 09:57:20
http://php5.kiev.ua/manual/ru/function.strrchr.html
i just recently did a function, that uses strrchr to format - let's say a currency - with 2 decimals. can also be done using number_format but you may NOT always want an automatic rounding of your decimals. thats there this function comes in handy:

<?php
function formatTwoDecimals($value$trim)
{
   
$after_comma substr(strrchr($value$trim), 03);
   
$in_front_of_comma = (int) $value;
   
$final $in_front_of_comma $after_comma;

   return 
$final;
}

echo 
formatTwoDecimals("365.6078985"".");
?>

this will produce
365.60

instead of
365.61
which will show up then you use number_format.
2007-08-01 19:32:34
http://php5.kiev.ua/manual/ru/function.strrchr.html
Автор:
strrchr is useful also in determining file extensions.

Here is a sample code that determines the file type based on its file extension. This is useful in displaying the files in your page, without using the database for the file description list.

<?php
 
/* File Extension Display using arrays
     by: Emmanuel Quiban (Philippines)
     BSCS 2002, AdU
     21-May-2008
 */

 // Sample file
 
$filesample "Mydocu.doc";

 
//Array for file description. You can expand the array list further with other file types you want
 
$filedes = array(
               
"Microsoft Excel Worksheet",
               
"Microsoft Word Document",
               
"Adobe Reader PDF File");

 
//Array for file extensions. Please take note that positions between the two arrays should be in sync with each other for correct file description.
 
$fileext = array(".xls"".doc"".pdf");

 
//This gets the file extension
 
$ext strrchr($filesample,'.');

 
//This conditional statement checks if the file extension given is in the array and matches it with the file description
 
if (in_array($ext,$fileext)) {

       
//Search the array
       
$ext2 array_search($ext$fileext);

       
//Since the result of the array_search is in integer, you can now assign it as an array value
       
$filetype $filedes[$ext2];

       
//Show the result
       
echo $filetype;
 } else {
       
$filetype "Unknown file type";
 }
?>
-----
The output of the script above is:
Microsoft Word Document

Let's say even if the filename looks like "My.Docu.doc", strrchr still gets the value ".doc" because it gets the last occurance of the dot.
-----

You can also make it as a function, like this:

<?php
 
/* File Extension Display using arrays
     by: Emmanuel Quiban (Philippines)
     BSCS 2002, AdU
     21-May-2008
 */
 
function getFileType($yourfile){

 
$filedes = array(
               
"CompuServe GIF Image",
               
"JPEG Image",
               
"Portable Network Graphics (PNG) Image"
               
);

 
$fileext = array(".gif",".jpg",".png");

 
$ext strrchr($yourfile,'.');
 if (
in_array($ext,$fileext)) {
       
$ext2 array_search($ext$fileext);
       
$filetype $filedes[$ext2];
 } else {
       
$filetype "Unknown file type";
 }

 return 
$filetype;
 }
?>
2008-05-21 10:32:16
http://php5.kiev.ua/manual/ru/function.strrchr.html
a KiSS variant of a previous note

<?php
function fcheck($f "test.doc")
{
 
$fd = array(".xls" => "Microsoft Excel Worksheet",".doc" => "Microsoft Word Document",".pdf" => "Adobe Reader PDF File");
 
$s $fd[strrchr($f,'.')];
 if (!empty(
$s))
 {
  return 
$s;
 }
 else
 {
  return 
"Unknown file type";
 }
}

?>
2008-05-29 10:29:49
http://php5.kiev.ua/manual/ru/function.strrchr.html
Here is my function that returns the type of a file. I fint it easier to add other types of files, and simplier than the rest i have seen around.

<?php
function findExt($filename){
   
$exts = array(
       
'.jpg' => 'image',
       
'.png' => 'image',
       
'.php' => 'php',
       
'.html' => 'html',
       
'.swf' => 'flash',
       
'.gz' => 'compressed',
       
'.tar' => 'compressed',
    );
   
$ext strrchr($filename,'.');
    if (
$exts[$ext]) { return $exts[$ext]; }
    else { return 
"unknown"; }
}
?>
2008-11-05 21:07:39
http://php5.kiev.ua/manual/ru/function.strrchr.html
this functions returns the full path of the current directory.
 
<?php

function CurrentFullPath()
{
   
$root $_SERVER['DOCUMENT_ROOT'] ;
   
$self $_SERVER['PHP_SELF'] ;
    return 
$root.mb_substr($self,0,-mb_strlen(strrchr($self,"/"))) ;
}

echo 
CurrentFullPath() ;

/*

If path is $path = "/home/me/www/pictures/control.php" ;

It will return :

/home/me/www/pictures

*/

?>
2009-05-23 20:30:57
http://php5.kiev.ua/manual/ru/function.strrchr.html
Easiest way to get the domain off of an email:

<?php

$domain 
strrchr($email'@');

// gets @gmail.com, with the preceding @.

?>

It's not perfect (see above in the manual), but it's pretty damn good.
2009-09-28 13:03:22
http://php5.kiev.ua/manual/ru/function.strrchr.html
<?php
/**
 * Removes the preceeding or proceeding portion of a string
 * relative to the last occurrence of the specified character.
 * The character selected may be retained or discarded.
 * 
 * Example usage:
 * <code>
 * $example = 'http://example.com/path/file.php';
 * $cwd_relative[] = cut_string_using_last('/', $example, 'left', true);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'left', false);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'right', true);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'right', false);
 * foreach($cwd_relative as $string) {
 *     echo "$string <br>".PHP_EOL;
 * }
 * </code>
 * 
 * Outputs:
 * <code>
 * http://example.com/path/
 * http://example.com/path
 * /file.php
 * file.php
 * </code>
 * 
 * @param string $character the character to search for.
 * @param string $string the string to search through.
 * @param string $side determines whether text to the left or the right of the character is returned.
 * Options are: left, or right.
 * @param bool $keep_character determines whether or not to keep the character.
 * Options are: true, or false.
 * @return string
 */
function cut_string_using_last($character$string$side$keep_character=true) {
   
$offset = ($keep_character 0);
   
$whole_length strlen($string);
   
$right_length = (strlen(strrchr($string$character)) - 1);
   
$left_length = ($whole_length $right_length 1);
    switch(
$side) {
        case 
'left':
           
$piece substr($string0, ($left_length $offset));
            break;
        case 
'right':
           
$start = (- ($right_length $offset));
           
$piece substr($string$start);
            break;
        default:
           
$piece false;
            break;
    }
    return(
$piece);
}
?>
2011-03-30 16:07:24
http://php5.kiev.ua/manual/ru/function.strrchr.html

    Поддержать сайт на родительском проекте КГБ