How to use strings in PHP

You can define a string using this notation:

$name = 'Flavio'; //string defined with single quotes

$name = "Flavio"; //string defined with double quotes

The big difference between using single and double quotes is that with double quotes we can expand variables in this way:

$test = 'an example';

$example = "This is $test"; //This is an example

and with double quotes we can use escape characters (think new lines \n or tabs \t):

$example = "This is a line\nThis is a line";

/*
output is:

This is a line
This is a line
*/

PHP offers you a very comprehensive functions in its standard library (the library of functionalities offered by default by the language).

First, we can concatenate two strings using the . operator:

$firstName = 'Flavio';
$lastName = 'Copes';

$fullName = $firstName . ' ' . $lastName;

We can check the length of a string using the strlen() function:

$name = 'Flavio';
strlen($name); //6

A function is composed of an identifier (strlen in this case) followed by parentheses. Inside those parentheses, we pass one or more arguments to the function. In this case, we have one argument.

The function does something and when it’s done it can return a value. In this case, it returns the number 6. If there’s no value returned, the function returns null.

We’ll see how to define our own functions later.

We can get a portion of a string using substr():

$name = 'Flavio';
substr($name, 3); //"vio" - start at position 3, get all the rest
substr($name, 2, 2); //"av" - start at position 2, get 2 items

We can replace a portion of a string using str_replace():

$name = 'Flavio';
str_replace('avio', 'ower', $name); //"Flower"

Of course we can assign the result to a new variable:

$name = 'Flavio';
$itemObserved = str_replace('avio', 'ower', $name); //"Flower"

There are a lot more built-in functions you can use to work with strings.

Here is a brief non-comprehensive list just to show you the possibilities:

  • trim() strips white space at the beginning and end of a string
  • strtoupper() makes a string uppercase
  • strtolower() makes a string lowercase
  • ucfirst() makes the first character uppercase
  • strpos() finds the firsts occurrence of a substring in the string
  • explode() to split a string into an array
  • implode() to join array elements in a string

Full list on https://www.php.net/manual/en/book.strings.php

Download my free PHP Handbook!