PHP Tutorial menu

PHP Strings

A string is a piece of text, such as a name, a message or an address.

Single vs Double Quotes

You can write a string with single quotes '...' or double quotes "...". The difference: double quotes replace variables with their values, single quotes do not.

Example

php
<?php
$city = "Lahore";
echo "I live in $city.<br>";
echo 'I live in $city.';
Output
I live in Lahore.
I live in $city.

Inside double quotes, use curly braces when a variable touches other letters:

Example

php
<?php
$item = "mango";
echo "I bought 5 {$item}es.";
Output
I bought 5 mangoes.

Joining Strings

The dot . joins (concatenates) strings. .= adds to the end of an existing string.

Example

php
<?php
$first = "Ayesha";
$last = "Khan";
$full = $first . " " . $last;

$message = "Welcome, ";
$message .= $full;

echo $message;
Output
Welcome, Ayesha Khan

Do not use + to join strings in PHP. The plus sign is only for numbers.

Escape Characters

To put special characters inside a double-quoted string, use a backslash:

CodeMeaning
\"A double quote
\\A backslash
\nA new line (in the page source)
\$A dollar sign
\tA tab

Example

php
<?php
echo "The book \"PHP Basics\" costs \$15.";
Output
The book "PHP Basics" costs $15.

Useful String Functions

FunctionWhat it does
strlen($s)Number of characters (bytes)
strtoupper($s)Converts to CAPITALS
strtolower($s)Converts to small letters
ucfirst($s)Capitalises the first letter
trim($s)Removes spaces from both ends
str_replace($a, $b, $s)Replaces $a with $b
substr($s, $start, $length)Takes part of a string
str_contains($s, $part)true if $part is inside (PHP 8)
strpos($s, $part)Position of $part, or false

Example

php
<?php
$text = "  welcome to orangi town  ";
$clean = trim($text);

echo strlen($clean) . "<br>";
echo ucfirst($clean) . "<br>";
echo strtoupper($clean) . "<br>";
echo str_replace("orangi town", "Karachi", $clean) . "<br>";
echo substr($clean, 0, 7);
Output
22
Welcome to orangi town
WELCOME TO ORANGI TOWN
welcome to Karachi
welcome

Checking Text

Example

php
<?php
$email = "ali@example.com";

if (str_contains($email, "@")) {
    echo "Looks like an email address.";
} else {
    echo "Please enter a valid email.";
}
Output
Looks like an email address.

Formatting Numbers

number_format() adds thousand separators and decimals, which is useful for prices:

Example

php
<?php
$price = 1250000;
echo "Rs " . number_format($price);
echo "<br>";
echo number_format(1234.5, 2);
Output
Rs 1,250,000
1,234.50

Exercise

Exercise

What does this code show? $n = "Ali"; echo 'Hi $n';

Learn PHP with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp