How to find the second-to-last occurrence of a character within a string?

后端 未结 5 1078
别跟我提以往
别跟我提以往 2021-02-07 10:29

If possible, using only standard PHP functions like substr(), strrpos(), strpos(), etc.

5条回答
  •  悲哀的现实
    2021-02-07 11:26

    First, find the last position:

    $last = strrpos($haystack, $needle);
    if ($last === false) {
      return false;
    }
    

    From there, find the 2nd last:

    $next_to_last = strrpos($haystack, $needle, $last - strlen($haystack) - 1);
    

提交回复
热议问题