← PHP EnglishChapter 07 of 13

Strings

## Learning Objectives - Master string creation and manipulation - Understand heredoc and nowdoc syntax - Learn string functions - Work with regular expressions ## String Creation ### Quotes ```php ``` ### Concatenation ```php ``` ## Heredoc ### Basic Heredoc ```php ``` ### Heredoc with Indentation ```php

Welcome

Hello, $name!

HTML; echo $html; ?> ``` ### Nowdoc ```php ``` ## String Functions ### Length and Count ```php ``` ### Case Conversion ```php ``` ### Trimming ```php ``` ### Padding ```php ``` ### Substrings ```php ``` ### Finding and Replacing ```php ``` ### Replace with Count ```php ``` ### Replace Multiple ```php "Hi", "World" => "PHP" ]; $result = str_replace(array_keys($replacements), array_values($replacements), $str); echo $result; // Hi, PHP! ?> ``` ### Substring Count ```php ``` ### Substring Compare ```php 0 if a > b, 0 if equal ?> ``` ## String Formatting ### Explode and Implode ```php ``` ### Split String ```php ``` ### String to Array ```php ``` ## Formatting Output ### Number Formatting ```php ``` ### Money Formatting ```php formatCurrency($price, 'USD'); // $1,234.56 ?> ``` ### sprintf ```php ``` ### printf ```php ``` ## Character Functions ### ASCII Conversion ```php ``` ### Check Character Types ```php ``` ## Regular Expressions ### preg_match() ```php ``` ### preg_match_all() ```php ``` ### preg_replace() ```php ``` ### preg_split() ```php ``` ### Pattern Modifiers ```php ``` ## URL Strings ### urlencode/urldecode ```php ``` ### Parse URL ```php ``` ### Build Query String ```php "Alice", "age" => 25, "city" => "Paris" ]; http_build_query($data); // "name=Alice&age=25&city=Paris" http_build_query($data, "", "&", PHP_QUERY_RFC3986); // URL-encoded properly ?> ``` ## JSON Strings ### Encode/Decode ```php "Alice", "age" => 25]; $json = json_encode($data); // '{"name":"Alice","age":25}' $decoded = json_decode($json, true); // ["name" => "Alice", "age" => 25] ?> ``` ### JSON Options ```php ""]; json_encode($data, JSON_HEX_TAG); // Escapes HTML tags json_encode($data, JSON_PRETTY_PRINT); // Formatted output json_encode($data, JSON_UNESCAPED_UNICODE); // Unicode chars json_encode($data, JSON_FORCE_OBJECT); // Always object ?> ``` ## Summary - Strings: single quotes (literal), double quotes (interpolated) - Heredoc `<<

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →