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
$city = "Lahore";
echo "I live in $city.<br>";
echo 'I live in $city.';I live in Lahore. I live in $city.
Inside double quotes, use curly braces when a variable touches other letters:
Example
<?php
$item = "mango";
echo "I bought 5 {$item}es.";I bought 5 mangoes.
Joining Strings
The dot . joins (concatenates) strings. .= adds to the end of an existing string.
Example
<?php
$first = "Ayesha";
$last = "Khan";
$full = $first . " " . $last;
$message = "Welcome, ";
$message .= $full;
echo $message;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:
| Code | Meaning |
|---|---|
\" | A double quote |
\\ | A backslash |
\n | A new line (in the page source) |
\$ | A dollar sign |
\t | A tab |
Example
<?php
echo "The book \"PHP Basics\" costs \$15.";The book "PHP Basics" costs $15.
Useful String Functions
| Function | What 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
$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);22 Welcome to orangi town WELCOME TO ORANGI TOWN welcome to Karachi welcome
Checking Text
Example
<?php
$email = "ali@example.com";
if (str_contains($email, "@")) {
echo "Looks like an email address.";
} else {
echo "Please enter a valid email.";
}Looks like an email address.
Formatting Numbers
number_format() adds thousand separators and decimals, which is useful for prices:
Example
<?php
$price = 1250000;
echo "Rs " . number_format($price);
echo "<br>";
echo number_format(1234.5, 2);Rs 1,250,000 1,234.50
Exercise
Exercise
What does this code show? $n = "Ali"; echo 'Hi $n';
