Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php string function to get substring before the last occurrence of a character

Tags:

php

$string = "Hello World Again". echo strrchr($string , ' '); // Gets ' Again' 

Now I want to get "Hello World" from the $string [The substring before the last occurrence of a space ' ' ]. How do I get it??

like image 453
ptamzz Avatar asked May 09 '11 15:05

ptamzz


People also ask

How do you find the last occurrence of a substring in a string in PHP?

The strrpos() function finds the position of the last occurrence of a string inside another string. Note: The strrpos() function is case-sensitive. Related functions: strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)

Which PHP function is used to find the position of the last occurrence of a substring inside another string?

The strrpos() is an in-built function of PHP which is used to find the position of the last occurrence of a substring inside another string.

How do you find the position of the first occurrence of a substring in a string in PHP?

The strpos() function finds the position of the first occurrence of a string inside another string. Note: The strpos() function is case-sensitive.

How do you find the last occurrence of a character?

strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .


2 Answers

$string = "Hello World Again"; echo substr($string, 0, strrpos( $string, ' ') ); //Hello World 

If the character isn't found, nothing is echoed

like image 144
meouw Avatar answered Sep 24 '22 08:09

meouw


This is kind of a cheap way to do it, but you could split, pop, and then join to get it done:

$string = 'Hello World Again'; $string = explode(' ', $string); array_pop($string); $string = implode(' ', $string); 
like image 27
sdleihssirhc Avatar answered Sep 23 '22 08:09

sdleihssirhc