What is a string in PHP?
Strings in PHP are sequences of characters in which a character is equivalent to a byte. Since a byte can only represent 256 characters, a PHP string cannot support Unicode strings natively. String variables in PHP can contain alphanumeric characters. To create a string in PHP, you can use: single quotes ('...'), double-quoted strings ("..."), and Heredoc syntax (<<<). PHP provides a rich set of built-in functions for concatenating, replacing, interpolating, splitting, and comparing strings. You can also convert string to int, convert string to lowercase, convert string to array and find the length of a string.
How to extract a substring from a PHP string?
To extract a substring from a string in PHP, you can use the built-in substr() function. The following is the syntax of the substr() function:
Where:
- $string (required): the input string;
- $offset (required): the position at which the function starts extracting the substring. In PHP, indexing starts from 0. If a negative value is specified, then the function will return a substring beginning at the $offset from the end of the string;
- $length (optional): the length of the part of the string to be cut off from the original string. If the integer is positive, this refers to starting at $offset and extracting the length from the beginning. If the integer is negative, then it relates to starting at $offset and extracting the length from the end of the string.
PHP substr() Usage Examples
The following are examples of getting a substring from a string using substr():
Getting a substring from the string at a specified index
The following is an example of extracting a substring from a PHP string starting at the specified index and ending at the end of the string using substr() function:
Getting a substring from the end of the string
To get a substring from the end of a PHP string using the substr() function, you need to specify a negative $offset value. The last character in the input string has an index of -1. The following is an example of extracting a substring from the end of the PHP string using substr() function:
Getting substring from the middle of the string
To get a substring from the middle of a PHP string using the substr() function, you need to specify the position of the first character you want to extract ($offset) and the number of characters ($length). The following is an example of extracting a substring from the middle of the PHP string using substr() function:
How to get a substring from a PHP string from a Non-Ascii string?
To extract a substring from a string containing a non-ASCII character, you can use the mb_substr() function. The mb_substr() function is similar to substr(), except that it has an extra encoding argument. The following is an example of extracting a substring from a non-ASCII string using the mb_substr() function: