Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : String Functions : strrchr

strrchr

Find the last occurrence of a character in a string (PHP 4, PHP 5)
string strrchr ( string haystack, string needle )

Example 2462. strrchr() example

<?php
// get last directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);

// get everything after last newline
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1 );
?>

Code Examples / Notes » strrchr

readless

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;
  }
}
?>


freakinunreal

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.


juancri

this functions returns the name of the current directory.
<?php
function currentd() {
   return substr(strrchr(`pwd`, '/'), 1);
}
?>


dchris1

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/"
?>


andfarm

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.


sekati

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 . "
" . $ns2);
?>


carlos dot lage

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;
}
?>


subbz2k

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

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


arcesis - gmail - com

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);
?>


marcokonopacki

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


primo anderson do sítio

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


Change Language


Follow Navioo On Twitter
addcslashes
addslashes
bin2hex
chop
chr
chunk_split
convert_cyr_string
convert_uudecode
convert_uuencode
count_chars
crc32
crypt
echo
explode
fprintf
get_html_translation_table
hebrev
hebrevc
html_entity_decode
htmlentities
htmlspecialchars_decode
htmlspecialchars
implode
join
levenshtein
localeconv
ltrim
md5_file
md5
metaphone
money_format
nl_langinfo
nl2br
number_format
ord
parse_str
print
printf
quoted_printable_decode
quotemeta
rtrim
setlocale
sha1_file
sha1
similar_text
soundex
sprintf
sscanf
str_getcsv
str_ireplace
str_pad
str_repeat
str_replace
str_rot13
str_shuffle
str_split
str_word_count
strcasecmp
strchr
strcmp
strcoll
strcspn
strip_tags
stripcslashes
stripos
stripslashes
stristr
strlen
strnatcasecmp
strnatcmp
strncasecmp
strncmp
strpbrk
strpos
strrchr
strrev
strripos
strrpos
strspn
strstr
strtok
strtolower
strtoupper
strtr
substr_compare
substr_count
substr_replace
substr
trim
ucfirst
ucwords
vfprintf
vprintf
vsprintf
wordwrap
eXTReMe Tracker