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

FormInterpolates 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)

TaskFunction(s)Example
Lengthstrlenstrlen("hello") → 5
Slicesubstrsubstr("abcdef",1,3) → "bcd"
Findstrpos, striposstrpos("hello","lo") → 3
Contains(use strpos(...) !== false)
Replacestr_replace, str_ireplaceCase-sensitive / insensitive
Split / Joinexplode, implodeCSV parsing, join array to string
Trimtrim, ltrim, rtrimRemove whitespace/characters at ends
Casestrtoupper, strtolower, ucfirst, ucwordsTitle casing names
Repeatstr_repeatstr_repeat("-", 10)
Comparestrcmp, strcasecmp, strncmpLexicographic 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).

RegularMultibyte-safe
strlenmb_strlen
substrmb_substr
strposmb_strpos
strtolower/strtouppermb_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

PitfallWhyFix
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 implode at the end instead of repeated . in a loop.
  • Use strtr for multiple simple replacements (often faster than chained str_replace).
  • Avoid unnecessary regex — plain string funcs are faster.
  • Cache compiled regex if used repeatedly.

Practice Tasks

  1. Write slugify($title) → lowercase, trim, replace spaces with -, remove non-alphanumerics (keep hyphen).
  2. Given a full name " sonu kumar pandit ", trim, title-case, and output "Sonu Kumar Pandit".
  3. Extract the domain from an email using strpos/substr and again using regex.
  4. Safely render a user comment into HTML with htmlspecialchars.
  5. 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.