Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

strrchr

(PHP 3, PHP 4, PHP 5)

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

Описание

string strrchr ( string haystack, char needle )

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

Если подстрока needle не найдена, возвращает FALSE.

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

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

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

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

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

С версии PHP 4.3.0 strrchr() безопасна для обработки данных в двоичной форме.

См. также описание функций strstr(), substr() и stristr().



strrev> <strpos
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
strrchr
subbz2k at yahoo dot de
01-Aug-2007 04:32
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), 0, 3);
  
$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.
repley at freemail dot it
11-Aug-2006 06:57
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($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.
       $a = array($left, $right);
       return $a;
   }else{
       return false;
   }
}
?>

Repley
readless at gmx dot net
06-Jun-2006 07:55
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;
   }
}
?>
repley at freemail dot it
18-May-2006 03:09
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($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.
       $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
sekati at gmail dot com
08-Apr-2006 05:43
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);
?>
freakinunreal at hotmail dot com
24-Dec-2005 10:54
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.
arcesis - gmail - com
11-Nov-2005 06:26
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);
?>
Primo Anderson Do S
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571