PHP 8.3.4 Released!

strrchr

(PHP 4, PHP 5, PHP 7, PHP 8)

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

Описание

strrchr(string $haystack, string $needle, bool $before_needle = false): string|false

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

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

haystack

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

needle

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

До PHP 8.0.0, если параметр needle — не строка, он преобразовывается в целое число и трактуется как код символа. Это поведение устарело с PHP 7.3.0 и полагаться на него крайне не рекомендуется. В зависимости от предполагаемого поведения, параметр needle должен быть либо явно приведён к строке, либо должен быть выполнен явный вызов функции chr().

before_needle

Если true, то функция strrchr() возвращает часть параметра haystack перед последним вхождением параметра needle (без учёта needle).

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

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

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

Версия Описание
8.3.0 Добавлен параметр before_needle.
8.0.0 Параметр needle теперь допускает пустую строку.
8.0.0 Передача целого числа (int) в needle больше не поддерживается.
7.3.0 Передача целого числа (int) в needle объявлена устаревшей.

Примеры

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

<?php
$ext
= strrchr('somefile.txt', '.');
echo
"Расширение файла: $ext \n";
$ext = $ext ? strtolower(substr($ext, 1)) : '';
echo
"Расширение файла: $ext";
?>

Вывод приведённого примера будет похож на:

Расширение файла: .txt
Расширение файла: txt

Примечания

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

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

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

add a note

User Contributed Notes 10 notes

up
30
matthewkastor at live dot com
12 years ago
<?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 ? 1 : 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($string, 0, ($left_length + $offset));
break;
case
'right':
$start = (0 - ($right_length + $offset));
$piece = substr($string, $start);
break;
default:
$piece = false;
break;
}
return(
$piece);
}
?>
up
12
sekati at gmail dot com
17 years ago
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($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}
// usage:
$ns = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 0));
$ns2 = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 1));
echo(
$ns . "<br>" . $ns2);
?>
up
7
dchris1 at bigpond dot net dot au
20 years ago
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($haystack, 0, $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/"
?>
up
6
readless at gmx dot net
17 years ago
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($haystack, 0, strrpos($haystack, $needle) + $l_inclusive);

//Switch value of $r_inclusive from 0 to 1 and viceversa.
$r_inclusive = ($r_inclusive == 0) ? 1 : 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;
}
}
?>
up
4
freakinunreal at hotmail dot com
18 years ago
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.
up
7
Primo Anderson Do S?tio
18 years ago
$filename = 'strrchr_test.php';
print strrchr( $filename, '.' );

Result:
.php

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

Result:
.php
up
1
marcokonopacki at hotmail dot com
20 years ago
<?

// 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)

?>
up
-4
carlos dot lage at gmail dot com
18 years ago
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($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
}
?>
up
-5
andfarm at thibs dot menloschool dot org
20 years ago
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.
up
-10
alex_bb23 at yahoo.co.uk
6 years ago
I think that a good way (I don't know if is the best one) to extract a portion from a string:
<?php

$image
= "image.name.jpg";
// get file extension
preg_replace("/.*\.(.*)$/", "$1", $last);
// will result: jpg

?>

Is faster that substr(strrchr...
To Top