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

Mary-Kate Olsen
Release: 2024-10-26 13:14:02
Original
779 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!