3

I would like to know the difference between the two different uses. I believe the difference in some what very subtle.

This is an explanation taken from the IBM reference manual. However maybe my english is bad, I just can't visualize the difference.

Maybe showing me an example of both cases would help me understand this better.

Here is the explanation from IBM :

The strchr subroutine returns a pointer to the first occurrence of the character specified by the Character (converted to an unsigned character) parameter in the string pointed to by the String parameter. A null pointer is returned if the character does not occur in the string. The null byte that terminates a string is considered to be part of the string.

The strrchr subroutine returns a pointer to the last occurrence of the character specified by the Character (converted to a character) parameter in the string pointed to by the String parameter. A null pointer is returned if the character does not occur in the string. The null byte that terminates a string is considered to be part of the string.

Luke Shaheen
  • 4,262
  • 12
  • 52
  • 82
hayonj
  • 1,429
  • 3
  • 21
  • 28
  • `strchr("Bananna", 'n')` vs. `strrchr("Bananna", 'n')` should illustrate the difference. – jedwards Mar 31 '13 at 02:05
  • 1
    Why are you reading this IBM manual instead of the php.net manual? Do you have a link to the IBM manual you are referring to? – Luke Shaheen Mar 31 '13 at 02:09

2 Answers2

10

strchr is an alias of strstr:

Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.

strrchr:

This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.

strchr starts at the first occurrence, strrchr starts at the last occurrence.

Luke Shaheen
  • 4,262
  • 12
  • 52
  • 82
  • I ended up doing it like so and it worked : `code`$trim = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1); `code` – hayonj Mar 31 '13 at 19:40
  • For strrchr, only the first character in $needle is used. strrchr("example_example_extra", "example") will return "extra" and not "example_extra" – Hatzegopteryx Dec 12 '18 at 19:59
9

strchr finds the first occurrence and strrchr (r - reverse) finds the last occurrence of a character or string

$s = 'This is a test';
$first = strchr($s, 's');
$last = strrchr($s, 's');
  • $first contains s is a test
  • $last contains st
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198