alecwhardy
alecwhardy

Reputation: 2718

How do I get the last part of a string in 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).

Upvotes: 10

Views: 19064

Answers (6)

Max Cuttins
Max Cuttins

Reputation: 613

Just do:

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

Upvotes: 3

Mike
Mike

Reputation: 8877

I realise this question is from 2012, but the answers here are all inefficient. There are string functions built into PHP to do this, rather than having to traverse the string and turn it into an array, and then pick the last index, which is a lot of work to do something quite simple.

The following code gets the last occurrence of a string within a string:

strrchr($string, '.'); // Last occurrence of '.' within a string

We can use this in conjunction with substr, which essentially chops a string up based on a position.

$string = 'this.is.a.sample';
$last_section = substr($string, (strrchr($string, '-') + 1));
echo $last_section; // 'sample'

Note the +1 on the strrchr result; this is because strrchr returns the index of the string within the string (starting at position 0), so the true 'position' is always 1 character on.

Upvotes: 7

Ajay Patel
Ajay Patel

Reputation: 5418

$string = "this.is.another.sample.of.it";
$result = explode('.', $string); // using explode function

print_r($result); // whole Array

Will give you

result[0]=>this;
result[1]=>is;
result[2]=>another;
result[3]=>sample;
result[4]=>of;
result[5]=>it;

Display any one you want (ex. echo result[5];)

Upvotes: 0

phpmeh
phpmeh

Reputation: 1792

https://www.php.net/strpos

$haystack = "this.is.another.sample.of.it"; 
$needle = "sample"; 
$string = substr( $haystack, strpos( $haystack, $needle ), strlen( $needle ) ); 

Upvotes: 3

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

$new_string = explode(".", "this.is.sparta");
$last_part = $new_string[count($new_string)-1];

echo $last_part;    // prints "sparta".

Upvotes: 0

Menztrual
Menztrual

Reputation: 41587

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

echo end($contents); // displays 'it'

Upvotes: 31

Related Questions