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!