PHP ยท Chapter 8 of 44

PHP Strings & String Functions

A string is a sequence of characters, like "Hello, World!". PHP provides many built-in functions to work with strings, such as measuring their length, changing case, searching for substrings, and replacing text.

Strings can be written with single quotes or double quotes. Double-quoted strings support variable interpolation and escape sequences like \n, while single-quoted strings treat almost everything literally.

Syntax
strlen($str);
str_replace($search, $replace, $str);

Common string functions

strlen() returns the length of a string, strtoupper() and strtolower() change case, str_replace() replaces text, and substr() extracts part of a string.

Concatenation

The dot (.) operator joins strings together, and the .= operator appends a value to an existing string variable.

Example 1 (php)
<?php
  $text = "Hello, World!";
  echo strlen($text);
?>
Output
13

strlen() counts the number of characters in the string, including punctuation and spaces.

Example 2 (php)
<?php
  $text = "I like cats";
  echo str_replace("cats", "dogs", $text);
?>
Output
I like dogs

str_replace() searches for 'cats' and replaces it with 'dogs' in the string.

Key points

  • Strings can use single or double quotes.
  • Double-quoted strings support variable interpolation and escape sequences.
  • The dot (.) operator concatenates strings.
  • PHP has dozens of built-in string functions like strlen(), strtoupper() and substr().
๐Ÿ’ก Note: Use single quotes for plain text without variables โ€” it is slightly faster since PHP skips parsing for interpolation.

๐Ÿ“ Quick Quiz

1. Which operator joins two strings together?

2. Which function returns the length of a string?

3. Which quote type supports variable interpolation?