Introduction
Almost everything a web app handles is text: names, emails, messages, passwords, page titles. In PHP, text is a string — characters inside quotes. And PHP gives you a whole toolbox for working with strings: measuring them, searching inside them, changing their case, cutting them up and joining them back together.
Two facts from PH.2 return here with more weight. First, double quotes replace variables inside them ("Hello $name"), single quotes do not. Second, the dot . joins strings — the operator you will use more than any other in this lesson.
(Roman Urdu: String matlab "likha hua text" — quotes ke andar. Double quotes variable ki value daal deti hain, single quotes nahi.)
Strings also hide the most common validation jobs in web development: is this email long enough? Does this password contain a number? Is this name empty? The functions in this lesson answer all three.
Key points
- A string is text in quotes.
"Ali"and'Ali'are both strings — but they behave differently with variables inside. - Double quotes interpolate:
"Hello $name"becomes Hello Ali. Single quotes do not:'Hello $name'stays as written. strlen($str)counts characters, including spaces. An empty string has length 0.strtoupper($str)/strtolower($str)change the case of the whole string.strpos($haystack, $needle)finds where a piece of text starts — or returnsfalsewhen it is not there.str_replace($find, $with, $str)swaps one piece of text for another, everywhere it appears.substr($str, $start, $length)cuts out part of a string.trim($str)removes spaces from both ends — essential for form input.explode($sep, $str)splits a string into an array;implode($glue, $arr)joins an array back into a string.htmlspecialchars($str)turns<,>and&into safe text — never print user input on a page without it.
Examples
Example 1 — Length and case
<?php
$name = "Ali Ahmed";
echo strlen($name);
echo "<br>";
echo strtoupper($name);
echo "<br>";
echo strtolower($name);
?>What you will get:
9
ALI AHMED
ali ahmedstrlen counts 9 characters — the space counts too. Case functions return a new string; the original $name is unchanged.
Example 2 — Searching: strpos and its false trap
<?php
$email = "[email protected]";
$pos = strpos($email, "@");
echo $pos;
echo "<br>";
if (strpos($email, "@") !== false) {
echo "Looks like an email";
}
?>What you will get:
3
Looks like an email@ sits at position 3 (counting from 0). The trap: when the needle is at position 0, strpos returns 0, and 0 == false is true in PHP — so a careless == false check lies to you. Always compare with !== false.
Example 3 — Replacing and cutting
<?php
$msg = "Hello, Ali! Welcome, Ali!";
echo str_replace("Ali", "Sara", $msg);
echo "<br>";
echo substr("Hello, World!", 0, 5);
echo "<br>";
echo substr("Hello, World!", 7);
?>What you will get:
Hello, Sara! Welcome, Sara!
Hello
World!str_replace swaps every occurrence. substr with a start and a length cuts a piece; with only a start it takes everything from there to the end.
Example 4 — trim: cleaning form input
<?php
$typed = " Ali ";
echo strlen($typed);
echo "<br>";
$clean = trim($typed);
echo strlen($clean);
echo "<br>";
echo "[" . $clean . "]";
?>What you will get:
9
3
[Ali]Users type accidental spaces before and after their input. trim removes them from both ends. Always trim form values before checking or saving them.
Example 5 — explode and implode: strings become arrays and back
<?php
$csv = "apple,banana,mango";
$fruits = explode(",", $csv);
echo $fruits[1];
echo "<br>";
echo implode(" - ", $fruits);
?>What you will get:
banana
apple - banana - mangoexplode splits on the comma into an array; implode joins the array with a glue string. Together they are the simplest way to handle comma-separated data.
Example 6 — Printing user text safely
<?php
$comment = "<script>alert('hack');</script> Nice post!";
echo htmlspecialchars($comment);
?>What you will get:
<script>alert('hack');</script> Nice post! — shown as harmless text, not run as code.htmlspecialchars turns < into <, so the browser shows the text instead of running it. Without this, a visitor's comment could run JavaScript on every other visitor's page. Never skip it.
Quick recap
- Double quotes replace variables; single quotes do not;
.joins strings. strlencounts;strtoupper/strtolowerchange case.strposfinds text — compare with!== false, never== false.str_replaceswaps;substrcuts;trimcleans spaces.explodesplits to an array;implodejoins back.htmlspecialcharsmakes user text safe to print — always use it.
Common mistakes
- Checking strpos with
== false— when the text is found at position 0,0 == falseis true and your code thinks it was not found. Fix: always use!== false. - Forgetting that strlen counts bytes, not letters, for Urdu/Arabic text — multibyte characters count as more than one. Fix: use
mb_strlen($str)for non-English text. - Printing user input without htmlspecialchars — a
<script>in a comment runs on every visitor's browser. Fix: escape every user value you print. - Using single quotes and expecting the variable —
'Hello $name'prints the dollar sign. Fix: double quotes, or join with.. - Comparing strings with
==when case matters —"Ali" == "ali"is false. Fix: comparestrtolower($a) == strtolower($b)when case should not matter. - Forgetting trim on form values —
" Ali "fails an exact-match check against"Ali". Fix: trim every value the moment it arrives. - Treating
substrpositions as starting at 1 — strings start at 0, sosubstr($s, 1, 3)skips the first character. Fix: count from 0.
Practice
- Store your full name and print its length, its uppercase version, and its lowercase version.
- Use
strposto check whether "example.com" contains "@" — write the check with!== falseand test it with an address that has no "@". - Replace every "chai" with "coffee" in the sentence "I like chai. Chai is great." — how many changed, and why?
- Take
" Sara "with spaces, trim it, and print the length before and after. - Split
"red,green,blue"withexplode, print the second colour, then join the array with" + "usingimplode. - Cut the first 5 characters from
"Hello, World!"withsubstr— then cut everything from position 7 to the end. - Print the string
<b>Hi</b>twice: once raw (watch it turn bold) and once withhtmlspecialchars(watch it show as text) — write down in one line why the second one is the safe way.
Practice quiz
Tap an answer to check it — a right answer turns green, a wrong one turns red and shows the right answer. Nothing is scored or saved; this is just for practice.
1. What does strlen("Ali Ahmed") give?
2. How must you test the result of strpos()?
3. Why print user text with htmlspecialchars()?