phpPHP
Module 8: StringsBeginner45 min read

PHP Strings, Heredoc/Nowdoc, UTF-8 Multibyte (mb_*) & Context-Aware Escaping

Master string interpolation, heredoc/nowdoc, PHP 8 str_contains/str_starts_with, UTF-8 multibyte mb_strlen, and why escaping depends on output context.

Key Takeaways & Core Concepts
  • Single quotes (`'...'`): Literal, no variable interpolation.
  • Nowdoc (`<<<'EOT'`): Multiline literal without interpolation.

1. Quotes, Heredoc & Nowdoc

  • Single quotes (`'...'`): Literal, no variable interpolation.
  • Double quotes (`"..."`) & Heredoc (`<<<EOT`): Interpolate variables ({$user->name}) and escape sequences.
  • Nowdoc (`<<<'EOT'`): Multiline literal without interpolation.
1. PHP 8 str_contains, mb_strlen & htmlspecialchars
1<?php
2$text = "CodeZov PHP 8";
3var_dump(str_contains($text, "PHP"));
4$hindi = "नमस्ते";
5echo "Bytes: " . strlen($hindi) . ", Chars: " . mb_strlen($hindi, "UTF-8") . "\n";
6echo htmlspecialchars("<script>alert(1)</script>", ENT_QUOTES, "UTF-8") . "\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
6 lines
Note: Shows UTF-8 byte vs character difference and safe HTML entity encoding.

2. Bytes vs. UTF-8 Characters & PHP 8 String Functions

strlen("नमस्ते") returns byte count (18), whereas mb_strlen("नमस्ते", "UTF-8") returns character count (6)! PHP 8.0 added str_contains(), str_starts_with(), and str_ends_with().

3. Output-Context Security

Always escape HTML output with htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') to prevent XSS; never use string escaping for SQL (use PDO prepared statements instead!).

Practice & AssessmentPHP Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)