On 02.09.2024 at 13:17, Vincent Langlet wrote: > I was today old when I discovered the big difference between strchr and > strrchr in the way they handle needle with multiple characters. > > It's explained in the doc https://www.php.net/manual/en/function.strrchr.php > - If needle contains more than one character, only the first is used. This > behavior is different from that of strstr() > <https://www.php.net/manual/en/function.strstr.php>. > > You can see an example https://3v4l.org/7j5ab > > I feel like this behavior has no benefit (if I want to look for the first > character, I can pass `substr($needle, 0, 1)` instead) and is just > error-prone. > > Is there a reason for such behavior ? Would it be easy to change it (I have > no knowledge at all in C and in the existing PHP code) ?
strchr() is an alias of strstr(), and I would always use the latter name, because strchr() is indeed confusing. Anyhow, strstr() is very useful in C, but not so much in PHP, since in PHP it will always allocate a new string, even if that is not needed. Now, comparing strstr() and strrchr() is of course still possible, but different behavior is less astonishing. Of course, strrchr() could warn or even throw if $needle has more than one character, but that may unnecessarily break code for a small benefit. Christoph