Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting strings in PHP and get last part

Tags:

string

php

I need to split a string in PHP by "-" and get the last part.

So from this:

abc-123-xyz-789

I expect to get

"789"

This is the code I've come up with:

substr(strrchr($urlId, '-'), 1) 

which works fine, except:

If my input string does not contain any "-", I must get the whole string, like from:

123

I need to get back

123

and it needs to be as fast as possible.

like image 219
Raphael Jeger Avatar asked Jun 10 '13 18:06

Raphael Jeger


People also ask

How can I get the last part of a string in PHP?

The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.

How can I split a string into two parts in PHP?

PHP | explode() Function explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs.

How do I slice a string in PHP?

The substr() function used to cut a part of a string from a string, starting at a specified position. The input string. Refers to the position of the string to start cutting. A positive number : Start at the specified position in the string.

What is explode in PHP?

A built-in function in PHP that splits a string into different strings is known as explode(). The splitting of the string is based on a string delimiter, that is, explode in PHP function splits the string wherever the delimiter element occurs.


1 Answers

  • split($pattern,$string) split strings within a given pattern or regex (it's deprecated since 5.3.0)
  • preg_split($pattern,$string) split strings within a given regex pattern
  • explode($pattern,$string) split strings within a given pattern
  • end($arr) get last array element

So:

end(split('-',$str))  end(preg_split('/-/',$str))  $strArray = explode('-',$str) $lastElement = end($strArray) 

Will return the last element of a - separated string.


And there's a hardcore way to do this:

$str = '1-2-3-4-5'; echo substr($str, strrpos($str, '-') + 1); //      |            '--- get the last position of '-' and add 1(if don't substr will get '-' too) //      '----- get the last piece of string after the last occurrence of '-' 
like image 153
Wesley Schleumer de Góes Avatar answered Sep 26 '22 14:09

Wesley Schleumer de Góes