How to get the last part of a string in PHP

I have many lines 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 a โ€œpattern,โ€ or โ€œthis,โ€ or โ€œtoo.โ€

What is the most effective way to do this. Obviously, there are many ways to do this, but what is the best way to use the least resources (CPU and RAM).

+4
source share
6 answers
 $string = "this.is.another.sample.of.it"; $contents = explode('.', $string); echo end($contents); // displays 'it' 
+21
source

http://us3.php.net/strpos

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

Just do:

 $string = "this.is.another.sample.of.it"; $last = array_pop(explode('.', $string)); 
+1
source
 $new_string = explode(".", "this.is.sparta"); $last_part = $new_string[count($new_string)-1]; echo $last_part; // prints "sparta". 
0
source
 $string = "this.is.another.sample.of.it"; $result = explode('.', $string); // using explode function print_r($result); // whole Array 

Gives you

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

Show any desired (for example, echo result[5]; )

0
source

I understand that this question is from 2012, but the answers here are all ineffective. To do this, there are string functions built into PHP, instead of moving around the string and turning it into an array, and then selecting the last index, which is a lot of work to make something very simple.

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

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

We can use this in conjunction with substr , which essentially breaks the line depending on the position.

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

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

0
source

Source: https://habr.com/ru/post/1402172/


All Articles