PHP String Functions Explained with Examples

โšก Smart Summary

Strings in PHP are ordered collections of characters and one of the language’s core data types. This walkthrough shows the four ways to create strings, single quotes, double quotes, heredoc, and nowdoc, then demonstrates the most useful built-in string functions with examples.

  • ๐Ÿ”ค What Strings Are: A string is a sequence of characters and a core PHP data type used to hold text such as names, messages, and HTML.
  • Single Quotes: Single-quoted strings are literal; variables are not expanded, and only the escaped quote and backslash are interpreted.
  • Double Quotes: Double-quoted strings expand variables and interpret escapes like \n, making them ideal for dynamic text.
  • ๐Ÿ“„ Heredoc: Heredoc builds multi-line strings with variable expansion, without escaping the double quotes inside them.
  • ๐Ÿ”’ Nowdoc: Nowdoc works like single quotes for multi-line raw text, performing no parsing or variable expansion.
  • ๐Ÿ”ง String Functions: Functions such as strlen, strpos, substr, str_replace, and explode inspect and transform string values.
  • ๐Ÿค– AI Assist: AI tools can suggest the right string function for a task and generate cleaning or formatting helpers.

PHP Strings

What is String in PHP?

A string is a collection of characters. String is one of the data types supported by PHP.

String variables can contain alphanumeric characters. Strings are created when:

  • You declare a variable and assign string characters to it
  • You directly use PHP strings with the echo statement.
  • PHP string functions are language constructs that help you work with text.
  • Learning how strings work in PHP and how to manipulate them will make you a very effective and productive developer.

PHP Create Strings Using Single quotes with Example

Let us now look at the four different ways of creating and manipulating strings in PHP.

Creating PHP strings using single quotes: the simplest way to create a string is to use single quotes.

Let us look at an example that creates a simple string in PHP.

<?php
var_dump('You need to be logged in to view this page');
?>

Output:

string(42) "You need to be logged in to view this page"

If the single quote is part of the string value, it can be escaped using the backslash.

The code below illustrates how to escape a single quote.

<?php
echo 'I \'ll be back after 20 minutes';
?>

Output:

I'll be back after 20 minutes

PHP Create Strings Using Double quotes with Example

Double quotes are used to create relatively complex strings compared to single quotes.

Variable names can be used inside double quotes and their values will be displayed.

Let us look at an example.

<?php
$name = 'Alicia';
echo "$name is friends with kalinda";
?>

PHP Create Strings Using Double quotes

HERE,

  • The above example creates a simple string with the value of Alicia.
  • The variable name is then used in the string created using double quotes, and its value is interpolated at run time.

Output:

Alicia is friends with kalinda

In addition to variable interpolation, the double quote string can also escape more special characters such as “\n for a linefeed, \$ for the dollar sign” etc.

More examples. Let us suppose that we have the following code.

<?php $pwd = "pas$word"; echo $pwd; ?>

Output:

NOTICE : Undefined variable
pas

Executing the above code issues a notice, “Notice: Undefined variable”.

This is because $word is treated as a variable.

If we want the dollar sign to be treated as a literal value, we have to escape it.

<?php
$word = "word";
$pwd = "pas\$word";
echo $pwd; ?>

Output:

pas$word

PHP Heredoc with Example

The heredoc methodology is used to create fairly complex strings compared to double quotes.

Heredoc supports all the features of double quotes and allows creating string values with more than one line without PHP string concatenation.

Using double quotes to create strings that have multiple lines generates an error.

You can also use double quotes inside without escaping them.

The example below illustrates how the heredoc method is used to create string values.

<?php

$baby_name = "Shalon";

echo <<<EOT

When $baby_name was a baby,

She used to look like a "boy".

EOT;

?>

HERE,

<<<EOT is the string delimiter.

EOT is the acronym for end of text.

It should be defined on its own line at the beginning of the string and at the end.

Note: you can use anything you like in place of EOT.

PHP Heredoc

Output:

When Shalon was a baby, She used to look like a "boy".

PHP Nowdoc with Example

The nowdoc string creation method is similar to the heredoc method but works the way single quotes work.

No parsing takes place inside the nowdoc.

Nowdoc is ideal when working with raw data that does not need to be parsed.

The code below shows the nowdoc implementation.

<?php

$baby_name = "Shalon";

$my_variable = <<<'EOT'

When $baby_name was a baby,

She used to look like a "boy".

EOT;

echo $my_variable;

?>

Output:

When $baby_name was a baby, She used to look like a "boy".

PHP String Function Examples

String functions in PHP are used to manipulate string values.

We are now going to look at some of the commonly used string functions in PHP.

Function Description Example Output
strtolower Used to convert all string characters to lower case letters echo strtolower(‘Benjamin’); outputs benjamin
strtoupper Used to convert all string characters to upper case letters echo strtoupper(‘george w bush’); outputs GEORGE W BUSH
strlen The string length function is used to count the number of characters in a string. Spaces in between characters are also counted echo strlen(‘united states of america’); 24
explode Used to convert strings into an array variable $settings = explode(‘;’, “host=localhost; db=sales; uid=root; pwd=demo”); print_r($settings); Array ( [0] => host=localhost [1] => db=sales [2] => uid=root [3] => pwd=demo )
substr Used to return part of the string. It accepts three basic parameters: the string to be shortened, the starting position, and the number of characters to be returned. $my_var = ‘This is a really long sentence that I wish to cut short’;echo substr($my_var,0, 12).’…’; This is a re…
str_replace Used to locate and replace specified string values in a given string. The function accepts three arguments: the text to be replaced, the replacement text, and the text that is analyzed. echo str_replace (‘the’, ‘that’, ‘the laptop is very expensive’); that laptop is very expensive
strpos Used to locate and return the position of a character or characters within a string. This function accepts two arguments. echo strpos(‘PHP Programming’,’Pro’); 4
sha1 Used to calculate the SHA-1 hash of a string value echo sha1(‘password’); 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
md5 Used to calculate the MD5 hash of a string value echo md5(‘password’); 5f4dcc3b5aa765d61d8327deb882cf99
str_word_count Used to count the number of words in a string. echo str_word_count(‘This is a really long sentence that I wish to cut short’); 12
ucfirst Make the first character of a string value upper case echo ucfirst(‘respect’); Outputs Respect
lcfirst Make the first character of a string value lower case echo lcfirst(‘RESPECT’); Outputs rESPECT

FAQs

Use the dot operator to join strings, for example $full = $first . ‘ ‘ . $last;. You can also append to an existing string with the .= operator, which adds text to the end of the variable.

In PHP 8, use str_contains($haystack, $needle), which returns true or false. In older versions, use strpos() and check that the result is not identical to false, since a match at position 0 is falsy.

PHP strings are mutable and can be indexed like arrays. Read a character with $str[0] and even change it with $str[0] = ‘H’. The index is zero based, so the first character is at position 0.

Yes. AI can write helpers that trim whitespace, strip tags, normalize case, or slugify text, combining functions like trim, strip_tags, and preg_replace. Review the rules so they match your exact input.

Yes. Describe the goal, such as finding, replacing, or splitting text, and AI can point you to functions like strpos, str_replace, substr, or explode, and show a short example for each.

Summarize this post with: