Below are some common and useful PHP string functions.
PHP check if string is empty
1 2 3 |
if ($str !== '') { // $str is empty } |
PHP string split by character
1 |
$array = explode("delimiter", $str); |
PHP check if string contains
1 2 3 |
if (strpos($str, 'keyword') !== false) { // $str contains 'keyword' } |
PHP check string length
1 |
strlen($str) |
PHP replace part of a string
1 |
$str = str_replace('old', 'new', $str); |
PHP get substring of a string
1 2 3 4 5 6 7 8 9 10 |
substr($str,$start,$length); // skip first n chars substr($str,n); // get last n chars substr($str,-n); // get n to n+length chars substr($str,n, length); |
PHP insert insert a string into another string at position
1 2 |
// insert $new string into $string at position 4 $string = replace($string, $new, 4, 0); |
PHP trim spaces
Trim leading and trailing spaces from a string
1 |
trim($str); |