Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the last part of a string in PHP

Tags:

string

php

I have many strings that follow the same convention:

this.is.a.sample
this.is.another.sample.of.it
this.too

What i want to do is isolate the last part. So i want "sample", or "it", or "too".

What is the most efficient way for this to happen. Obviously there are many ways to do this, but which way is best that uses the least resources (CPU and RAM).

like image 624
alecwhardy Avatar asked Mar 19 '12 05:03

alecwhardy


People also ask

How can I get the last word in a sentence in PHP?

After getting the position of last occurring space we can easily get the last word in the string using the substr() function and store this in a new string variable. At last, we can use the strlen() function to find the length of the last word in the string.

What is substr () in PHP and how it is used?

substr in PHP is a built-in function used to extract a part of the given string. The function returns the substring specified by the start and length parameter. It is supported by PHP 4 and above. Let us see how we can use substr() to cut a portion of the string.

How can I get the first 3 characters of a string in PHP?

To get the first n characters of a string, we can use the built-in substr() function in PHP. Here is an example, that gets the first 3 characters from a following string: <? php echo substr("Google", 0, 3); ?>

How do you remove portion of a string before a certain character in PHP?

The chop() function removes whitespaces or other predefined characters from the right end of a string.


1 Answers

$string = "this.is.another.sample.of.it";
$contents = explode('.', $string);

echo end($contents); // displays 'it'
like image 147
Menztrual Avatar answered Sep 23 '22 12:09

Menztrual