Home  >  Article  >  Backend Development  >  How to Get the Substring Before the Last Character Occurrence in PHP?

How to Get the Substring Before the Last Character Occurrence in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 13:14:02780browse

How to Get the Substring Before the Last Character Occurrence in PHP?

Getting Substring Before Last Character Occurrence in PHP

In PHP, the strrchr() function finds the last occurrence of a character in a string. However, suppose you need to retrieve the substring preceding the last occurrence of a specific character. In that case, you can follow these steps:

1. Identify the Position of the Last Character Occurrence:

First, use strrpos() to determine the position of the last occurrence of the target character in the string. In your case, you want to find the position of the last space ' '.

<code class="php">$string = "Hello World Again";
$pos = strrpos( $string, ' '); </code>

2. Extract the Substring:

Once you have the position, use substr() to extract the substring up to that position.

<code class="php">echo substr($string, 0, $pos );</code>

This will output "Hello World", as desired.

Note: If the character is not found in the string, nothing will be echoed.

The above is the detailed content of How to Get the Substring Before the Last Character Occurrence in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn