Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Strings

A string is text: a user name, a page title, an error message. Almost every program works with strings.

Writing a string

A string is written in quotes:

<?php
 
echo 'Hello, world!';

Single and double quotes

Inside single quotes text is printed as is. Double quotes enable variable interpolation and escape sequences: \n is a line break, \t is a tab.

<?php
 
echo "First line\nSecond line";

To put a quote character inside a string, write a backslash before it:

<?php
 
echo "He said: \"Hello\"";

When you do not need interpolation, use single quotes — it shows at a glance that the string has no variables.

Concatenation

Strings are joined with the dot operator. The .= operator appends text to the end of a variable:

<?php
 
$first = 'John';
$last = 'Smith';
 
$full = $first . ' ' . $last;
$full .= '!';
 
echo $full; // John Smith!

String length

strlen() counts bytes, while mb_strlen() counts characters. For non-ASCII text such as Cyrillic the results differ:

<?php
 
echo strlen('привет'), "\n";    // 12
echo mb_strlen('привет');       // 6

Searching and case

<?php
 
var_dump(str_contains('Hello, world', 'world')); // bool(true)
 
echo mb_strtoupper('hello'), "\n"; // HELLO
echo mb_strtolower('HELLO');       // hello

str_contains() checks whether a string contains a fragment. The search is case-sensitive: "World" and "world" are different strings.

Substrings and replacing

mb_substr() cuts out part of a string: you give the start position (counting from zero) and the number of characters. str_replace() replaces every occurrence of one fragment with another:

<?php
 
echo mb_substr('Programming', 0, 3), "\n";           // Pro
echo str_replace('world', 'PHP', 'Hello, world!');   // Hello, PHP!

Extra whitespace

User input often arrives with spaces around it. trim() removes them:

<?php
 
var_dump(trim('  text  ')); // string(4) "text"

A common mistake

Functions without the mb_ prefix work on bytes and break non-ASCII text: strtoupper('привет') leaves the string unchanged, and substr() can cut a character in half. For text in languages other than English always use the mb_ versions.

Thanks for reading!

Donate to the site — we work hard for you.