October 29, 2026

PHP – Strings

In this tutorial, we would cover string manipulation in PHP.

Just like in other languages, string in PHP are a sequence of characters. Some examples of strings are given below:

$string1 = "You can learn PHP";
$string0 = ""; //this is an empty string
$string2 = 'This is a singly quoted string';

 

About singly and double-quoted strings

Singly quoted strings are just output literally. However, double quoted strings would replace any containing variables with the actual values of those variables. An example is given below

<?php
    $name = "Kindson";

    echo "My name is $name <br>";
    echo 'My name is $name';
?> 

The result of the above code is shown below

My name is Kindson
My name is $name

 

Escape Sequences

This are special combination of characters used certain operations such as:

  • \n represents the newline character
  • \r represents the carriage-return character
  • \t represents the tab character
  • \$ represents the dollar sign itself ($)
  • \” represents a single double-quote (“)
  • \\ represents a single backslash (\)

 

String Concatenation Operator

The dot (.) operator is used to concatenate two variables.

The strlen() function

This function is used to find the length of a string. For example

<?php
    echo strlen("Learning PHP is fun");
?>  

 

The strpos() function

This function is used to search for a string or character within a string. If it finds a match, then the position of the first match is found, else, it will return false.

 

Some useful String functions

I have made a list of some other string functions you should know. See the table below:

SN Name and Description
1 trim() – removes whitespaced from the left and right of a string
2 ltrim() – removes whitespaces from the beginning of a string
3 rtrim() – removes whitespaces from the end of a string
4 substr(str, start, stop) – finds a substring from
5 strncmp() – compares two strings
6 explode(int sep, string str) – splits a string into an array of strings based on a separator
7 strrev() – reverses a string
8 strstr() – finds the first occurrence of a string within a string
9 preg_match(pattern, str) – finds the first occurrence string pattern in string str.

Complete list of string functions can be found here