Tutorials › PHP Tutorial › PHP Strings and String Functions

PHP Strings and String Functions

16 min read · Lesson 7 of 24

A string is a piece of text: a name, a message, a whole HTML page. Most of what a PHP website does is build strings and send them to the browser, so string skills pay off quickly.

Single and double quotes

Both kinds of quotes create strings, but double quotes do extra work:

  • In double quotes, variables are replaced by their values and escape sequences such as \n (newline), \t (tab), \" (a double quote) and \$ (a literal dollar sign) work.
  • In single quotes, only \' and \\ are special. Everything else is printed exactly.
Example PHP
<?php
$shop = "Mama Mboga";
echo "Welcome to $shop's stall\n";
echo 'Welcome to $shop\'s stall' . "\n";
echo "Price: \$20 per bunch\n";
echo "He said \"asante\"\n";
Result
Welcome to Mama Mboga's stall
Welcome to $shop's stall
Price: $20 per bunch
He said "asante"
Open in editor
Tip: Use single quotes for plain text with no variables. Use double quotes when you want to insert variables. Either is fine; just be consistent.

Joining strings (concatenation)

The dot operator . joins strings together. The combined assignment .= adds text to the end of an existing string.

Example PHP
<?php
$first = "Otieno";
$last = "Odhiambo";
$full = $first . " " . $last;
echo $full . "\n";

$message = "Dear $first,";
$message .= " your results are ready.";
echo $message;
Result
Otieno Odhiambo
Dear Otieno, your results are ready.
Open in editor

Heredoc for longer text

For several lines of text with variables (such as an email body), a heredoc is neater than many concatenations. It starts with <<< and an identifier, and ends with the same identifier on its own line.

Example PHP
<?php
$name = "Akinyi";
$amount = 3500;
$email = <<<TEXT
Hello $name,
We received KSh $amount. Thank you!
Skope Digital Academy
TEXT;
echo $email;
Result
Hello Akinyi,
We received KSh 3500. Thank you!
Skope Digital Academy
Open in editor

A nowdoc (<<<'TEXT' with single quotes around the name) works the same way but does not replace variables.

Accessing single characters

Strings are indexed from 0. Use square brackets to read one character. A negative index counts from the end.

Example PHP
<?php
$word = "Nairobi";
echo $word[0] . "\n";
echo $word[3] . "\n";
echo $word[-1] . "\n";
Result
N
r
i
Open in editor

Common string functions

PHP has more than 100 built-in string functions. These are the ones you will use every week.

Length, words and case

Example PHP
<?php
$text = "learn php at skope";
echo strlen($text) . "\n";          // number of characters (bytes)
echo str_word_count($text) . "\n";  // number of words
echo strtoupper($text) . "\n";
echo ucfirst($text) . "\n";
echo ucwords($text) . "\n";
echo strtolower("KISUMU") . "\n";
Result
18
4
LEARN PHP AT SKOPE
Learn php at skope
Learn Php At Skope
kisumu
Open in editor

Searching

  • str_contains($haystack, $needle) returns true if the text contains the search word.
  • str_starts_with() and str_ends_with() check the beginning and end.
  • strpos() gives the position of the first match (or false if not found).
Example PHP
<?php
$phone = "+254712345678";
var_dump(str_starts_with($phone, "+254"));
var_dump(str_contains($phone, "345"));
var_dump(strpos($phone, "7"));
var_dump(strpos($phone, "9"));
Result
bool(true)
bool(true)
int(4)
bool(false)
Open in editor
Warning: strpos() returns 0 when the match is at the very start, and 0 looks like false in an if. Always compare with !== false, or use str_contains(), which returns a clean true/false.

Cutting and replacing

Example PHP
<?php
$date = "2026-03-15";
echo substr($date, 0, 4) . "\n";     // from index 0, 4 characters
echo substr($date, 5) . "\n";        // from index 5 to the end
echo substr($date, -2) . "\n";       // last 2 characters

$msg = "Pay at the bank";
echo str_replace("the bank", "M-Pesa", $msg) . "\n";
echo strrev("habari") . "\n";
Result
2026
03-15
15
Pay at M-Pesa
irabah
Open in editor

Trimming, padding and repeating

User input often has extra spaces. trim() removes whitespace from both ends (ltrim() and rtrim() do one side).

Example PHP
<?php
$input = "   [email protected]  ";
echo "[" . trim($input) . "]\n";
echo str_pad("7", 3, "0", STR_PAD_LEFT) . "\n";
echo str_repeat("=-", 5) . "\n";
Result
[[email protected]]
007
=-=-=-=-=-
Open in editor

Splitting and joining

explode() splits a string into an array; implode() joins an array into a string.

Example PHP
<?php
$csv = "Kisumu,Nakuru,Eldoret";
$towns = explode(",", $csv);
echo $towns[1] . "\n";
echo implode(" | ", $towns) . "\n";
echo count($towns) . " towns\n";
Result
Nakuru
Kisumu | Nakuru | Eldoret
3 towns
Open in editor

Formatting with sprintf()

sprintf() builds a string from a template with placeholders: %s for a string, %d for an integer, %.2f for a float with 2 decimals. printf() does the same but prints directly.

Example PHP
<?php
$name = "Kamau";
$items = 3;
$total = 1249.5;
echo sprintf("%s bought %d items for KSh %.2f", $name, $items, $total) . "\n";
printf("%05d\n", 42);
Result
Kamau bought 3 items for KSh 1249.50
00042
Open in editor

Multibyte (Unicode) strings

strlen() counts bytes, not characters. Letters like "é" or emoji take more than one byte, so the count can look wrong. The mb_ functions count real characters.

Example PHP
<?php
$word = "café";
echo strlen($word) . "\n";
echo mb_strlen($word) . "\n";
echo mb_strtoupper($word) . "\n";
Result
5
4
CAFÉ
Open in editor
Note: The mb_ functions need the mbstring extension. It is enabled in XAMPP and on almost every host. Use them whenever text may contain non-English characters.

When you print strings that came from users, always escape them with htmlspecialchars(). The Form Validation lesson explains why.

Exercise

Join the two strings with the concatenation operator.

echo "Jambo"  " Kenya";
Exercise

Use the right functions to count characters and to make text upper case.

echo ("Skope");
echo ("skope");
Exercise

Split the string into an array at each comma.

$parts = (",", "a,b,c");
Sign in or create a free account to track progress, earn XP, badges and a certificate.