Strings
Strings represent text data. This page covers literals, concatenation vs interpolation, HEREDOC/NOWDOC, common functions, multibyte-safe operations, regex, formatting, HTML-safety, and performance tips.
1) Literals: Single vs Double Quotes
| Form | Interpolates variables? | Escapes |
|---|---|---|
'single' | No | \\, \' |
"double" | Yes ("Hello $name") | Common escapes like \n \t \" \\ |
<?php
$name = "Sonu";
echo 'Hello $name'; // Hello $name
echo "Hello $name"; // Hello Sonu
// Use curly braces to avoid confusion:
echo "Hi, {$name}!";
?>
Concatenation vs Interpolation
<?php
// Concatenation with .
$msg1 = "Hello, " . $name . "!";
// Interpolation (double quotes)
$msg2 = "Hello, $name!";
?>
2) HEREDOC & NOWDOC (multiline)
Great for long text blocks. HEREDOC behaves like double quotes (interpolates); NOWDOC behaves like single quotes (no interpolation).
<?php
$name = "Sonu";
// HEREDOC
$about = <<<TEXT
Hello $name
Welcome to Codingwithsonu.com
TEXT;
// NOWDOC
$raw = <<<'TEXT'
Hello $name (not interpolated)
TEXT;
?>
3) Core Functions (Cheat Sheet)
| Task | Function(s) | Example |
|---|---|---|
| Length | strlen | strlen("hello") → 5 |
| Slice | substr | substr("abcdef",1,3) → "bcd" |
| Find | strpos, stripos | strpos("hello","lo") → 3 |
| Contains | (use strpos(...) !== false) | — |
| Replace | str_replace, str_ireplace | Case-sensitive / insensitive |
| Split / Join | explode, implode | CSV parsing, join array to string |
| Trim | trim, ltrim, rtrim | Remove whitespace/characters at ends |
| Case | strtoupper, strtolower, ucfirst, ucwords | Title casing names |
| Repeat | str_repeat | str_repeat("-", 10) |
| Compare | strcmp, strcasecmp, strncmp | Lexicographic comparison |
<?php
$s = " Hello, PHP! ";
$clean = trim($s); // "Hello, PHP!"
$pos = strpos($clean, "PHP"); // 7
$part = substr($clean, 7, 3); // "PHP"
$repl = str_replace("PHP", "World", $clean); // "Hello, World!"
$items = explode(",", "a,b,c"); // ['a','b','c']
$csv = implode("|", $items); // "a|b|c"
?>
4) Formatting with sprintf
Build formatted strings (padding, decimals, hex, percentages, etc.).
<?php
$price = 1234.5;
$txt = sprintf("₹%0.2f", $price); // "₹1234.50"
// Padding numbers
$id = sprintf("INV-%05d", 42); // "INV-00042"
// number_format for thousands separators
$nice = number_format(1234567.891, 2); // "1,234,567.89"
?>
5) Regular Expressions (Quick Start)
Use preg_match, preg_replace, preg_split. Patterns use delimiters like /.../. The i flag = case-insensitive.
<?php
// Validate simple email pattern (demo only; real email validation is complex)
$email = "user@example.com";
if (preg_match("/^[\w.\-]+@[\w.\-]+\.[A-Za-z]{2,}$/i", $email)) {
echo "Looks OK";
}
// Replace non-digits
$digits = preg_replace("/\D+/", "", "+91-98765 43210"); // "919876543210"
?>
6) Multibyte (Unicode-safe) Strings
For languages like Hindi/हिन्दी, Japanese/日本語, emojis, etc., use mb_* functions (enable mbstring extension).
| Regular | Multibyte-safe |
|---|---|
strlen | mb_strlen |
substr | mb_substr |
strpos | mb_strpos |
strtolower/strtoupper | mb_strtolower/mb_strtoupper |
<?php
$txt = "नमस्ते";
echo strlen($txt); // bytes (not characters)
echo mb_strlen($txt, "UTF-8"); // correct chars
?>
7) HTML Safety & Sanitization
When outputting user input into HTML, escape it to prevent XSS.
<?php
$input = "<script>alert('x')</script>";
$safe = htmlspecialchars($input, ENT_QUOTES, "UTF-8");
// <script> becomes harmless text
// Remove HTML tags if needed
$plain = strip_tags("<b>Hello</b> <i>World</i>"); // "Hello World"
?>
Tip: Always store strings as UTF-8; set correct headers:
header('Content-Type: text/html; charset=UTF-8');8) Common Pitfalls
| Pitfall | Why | Fix |
|---|---|---|
strpos() check with == false |
Position 0 is loosely equal to false | Use !== false to test “found” |
| Wrong length for Unicode | strlen counts bytes, not characters |
Use mb_strlen with UTF-8 |
| Unescaped HTML output | XSS risk | htmlspecialchars(..., ENT_QUOTES, 'UTF-8') |
| Costly string concatenation in loops | Creates many temporary strings | Collect to array and implode once |
9) Performance Tips
- Prefer
implodeat the end instead of repeated.in a loop. - Use
strtrfor multiple simple replacements (often faster than chainedstr_replace). - Avoid unnecessary regex — plain string funcs are faster.
- Cache compiled regex if used repeatedly.
Practice Tasks
- Write
slugify($title)→ lowercase, trim, replace spaces with-, remove non-alphanumerics (keep hyphen). - Given a full name
" sonu kumar pandit ", trim, title-case, and output"Sonu Kumar Pandit". - Extract the domain from an email using
strpos/substrand again using regex. - Safely render a user comment into HTML with
htmlspecialchars. - Split a paragraph into sentences (basic split on
.) and re-join with line breaks.
Next: Continue with Superglobals —
$_GET, $_POST, $_SERVER, $_SESSION, $_COOKIE, and secure input handling.