PHP Substring


Used to get the specified string from a string.

The correlation functions are as follows:

  • substr(): Get a portion of a string from a string
  • Strstr(): Finds the first occurrence of a string in another string and returns all characters from that position to the end of the string
  • Li>
  • subchr(): same as strstr()
  • strrchr(): Finds the last occurrence of a string in another string and returns all characters from that position to the end of the string

substr()

The substr() function is used to get a portion of a string and return a string.

grammar:

string substr(string string, int start [, int length])
The parameter is described as follows:
parameter Description
string the string to process
start string start position, starting at 0, negative starting at the specified end of the string
length Optional, the length of the string to return, the default is until the end of the string, the negative from the end of the string return

example:

echo substr('abcdef', 1); // output bcdef
echo substr('abcdef', 1, 2); // output bc
echo substr('abcdef', -3, 2); // output de
echo substr('abcdef', 1, -2); // output bcd

Tip

If start is negative and length is less than or equal to start, length is 0.


strstr()

Finds the first occurrence of a string in another string and returns all characters from that position to the end of the string, or FALSE if it is not found.

grammar:

string strstr(string string, string needle)
The parameter is described as follows:
parameter Description
string the string to process
needle The string to find, and if it is a number, search for characters that match the numeric ASCII value

example:


$Email = 'user@5idev.com';
$Domain = strstr($email, '@');
echo $domain; // output @ 5idev.com

The function is case-sensitive. For case insensitive lookups, use stristr().


strchr()

Same with strstr().


strrchr()

Finds the last occurrence of a string in another string and returns all characters from that position to the end of the string, or FALSE if it is not found.

grammar:

string strrchr(string string, string needle)

The function behaves the same as the strstr() function. The meaning of the parameters is described in the above strstr()function parameter description.

example:

$Str =" AAA | BBB | CCC ";
echo strrchr($str, " | ");

Run the example, the output:

| CCC

Combining the substr()function allows you to intercept everything behind a last-shown character:

$Str =" AAA | BBB | CCC ";
echo substr(strrchr($str, " | "), 1);



Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook