String Functions
Official PHP Documentation:
String Length and Character Access
Section titled “String Length and Character Access”String Length
Section titled “String Length”$text = "Hello World";$length = strlen($text); // 11
// For multibyte strings$text = "Héllo Wörld";$length = mb_strlen($text, 'UTF-8'); // 11Character Access
Section titled “Character Access”$text = "Hello";$firstChar = $text[0]; // 'H'$lastChar = $text[strlen($text) - 1]; // 'o'$thirdChar = $text{2}; // 'l' (curly braces syntax, deprecated)String Manipulation Functions
Section titled “String Manipulation Functions”Case Conversion
Section titled “Case Conversion”$text = "Hello World";
$upper = strtoupper($text); // "HELLO WORLD"$lower = strtolower($text); // "hello world"$title = ucwords($text); // "Hello World"$sentence = ucfirst(strtolower($text)); // "Hello world"Trimming
Section titled “Trimming”$text = "  Hello World  ";
$trimmed = trim($text); // "Hello World"$leftTrimmed = ltrim($text); // "Hello World  "$rightTrimmed = rtrim($text); // "  Hello World"
// Trim specific characters$text = "...Hello World...";$cleaned = trim($text, '.'); // "Hello World"String Searching
Section titled “String Searching”$text = "The quick brown fox jumps over the lazy dog";
// Find position of substring$pos = strpos($text, "fox"); // 16$pos = stripos($text, "FOX"); // 16 (case-insensitive)
// Check if string contains substringif (str_contains($text, "fox")) { // PHP 8+    echo "Found fox!";}
// Count occurrences$count = substr_count($text, "the"); // 1$count = substr_count(strtolower($text), "the"); // 2 (case-insensitive)String Formatting
Section titled “String Formatting”sprintf Function
Section titled “sprintf Function”$name = "John";$age = 25;$formatted = sprintf("Hello, %s! You are %d years old.", $name, $age);// "Hello, John! You are 25 years old."
// Number formatting$price = 1234.567;$formatted = sprintf("Price: $%.2f", $price); // "Price: $1234.57"printf Function
Section titled “printf Function”$name = "Alice";$score = 95.5;printf("Student: %-10s Score: %6.2f%%\n", $name, $score);// Output: "Student: Alice      Score:  95.50%"Number Formatting
Section titled “Number Formatting”$number = 1234567.89;
$formatted = number_format($number); // "1,234,568"$formatted = number_format($number, 2); // "1,234,567.89"$formatted = number_format($number, 2, ",", "."); // "1.234.567,89"String Replacement
Section titled “String Replacement”$text = "The quick brown fox";
// Replace all occurrences$newText = str_replace("fox", "dog", $text); // "The quick brown dog"
// Case-insensitive replacement$newText = str_ireplace("QUICK", "slow", $text); // "The slow brown fox"
// Replace multiple values$search = ["quick", "brown"];$replace = ["slow", "black"];$newText = str_replace($search, $replace, $text); // "The slow black fox"
// Count replacements$newText = str_replace("fox", "dog", $text, $count);echo "Made $count replacements";Substring Operations
Section titled “Substring Operations”$text = "Hello World";
// Extract substring$sub = substr($text, 0, 5); // "Hello"$sub = substr($text, 6); // "World"$sub = substr($text, -5); // "World" (from end)$sub = substr($text, -5, 3); // "Wor"
// Multibyte substring$text = "Héllo Wörld";$sub = mb_substr($text, 0, 5, 'UTF-8'); // "Héllo"String Splitting and Joining
Section titled “String Splitting and Joining”Explode and Implode
Section titled “Explode and Implode”// Split string into array$csv = "apple,banana,orange";$fruits = explode(",", $csv); // ["apple", "banana", "orange"]
// Join array into string$joined = implode(" | ", $fruits); // "apple | banana | orange"
// Limit splits$text = "one-two-three-four";$parts = explode("-", $text, 2); // ["one", "two-three-four"]String Tokenization
Section titled “String Tokenization”$text = "apple,banana;orange:grape";$token = strtok($text, ",;:");
while ($token !== false) {    echo $token . "\n";    $token = strtok(",;:");}// Outputs: apple, banana, orange, grapeString Encoding and Security
Section titled “String Encoding and Security”HTML Escaping
Section titled “HTML Escaping”$userInput = '<script>alert("XSS")</script>';$safe = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');// "<script>alert("XSS")</script>"
$decoded = htmlspecialchars_decode($safe);// Back to original stringURL Encoding
Section titled “URL Encoding”$url = "Hello World & More";$encoded = urlencode($url); // "Hello+World+%26+More"$rawEncoded = rawurlencode($url); // "Hello%20World%20%26%20More"
$decoded = urldecode($encoded); // Back to originalBase64 Encoding
Section titled “Base64 Encoding”$data = "Hello World";$encoded = base64_encode($data); // "SGVsbG8gV29ybGQ="$decoded = base64_decode($encoded); // "Hello World"Multibyte String Handling
Section titled “Multibyte String Handling”UTF-8 Support
Section titled “UTF-8 Support”// Set internal encodingmb_internal_encoding('UTF-8');
$text = "Héllo Wörld";$length = mb_strlen($text); // Correct length for multibyte$upper = mb_strtoupper($text); // "HÉLLO WÖRLD"$sub = mb_substr($text, 0, 5); // "Héllo"Character Encoding Conversion
Section titled “Character Encoding Conversion”$text = "Hello World";$converted = mb_convert_encoding($text, 'UTF-8', 'ISO-8859-1');
// Detect encoding$encoding = mb_detect_encoding($text, ['UTF-8', 'ISO-8859-1']);String Comparison
Section titled “String Comparison”Basic Comparison
Section titled “Basic Comparison”$str1 = "apple";$str2 = "Apple";
// Case-sensitive comparison$result = strcmp($str1, $str2); // > 0 (str1 > str2)
// Case-insensitive comparison$result = strcasecmp($str1, $str2); // 0 (equal)
// Natural order comparison$files = ["file1.txt", "file10.txt", "file2.txt"];usort($files, 'strnatcmp');// Result: ["file1.txt", "file2.txt", "file10.txt"]String Similarity
Section titled “String Similarity”$str1 = "programming";$str2 = "programing";
similar_text($str1, $str2, $percent);echo "Similarity: " . round($percent, 2) . "%";
// Levenshtein distance$distance = levenshtein($str1, $str2); // Number of edits neededAdvanced String Operations
Section titled “Advanced String Operations”String Hashing
Section titled “String Hashing”$password = "mySecretPassword";
// Simple hash (not secure for passwords)$md5 = md5($password);$sha1 = sha1($password);
// Secure password hashing$hash = password_hash($password, PASSWORD_DEFAULT);$isValid = password_verify($password, $hash);String Parsing
Section titled “String Parsing”// Parse URL$url = "https://example.com/path?param=value";$parsed = parse_url($url);/*Array(    [scheme] => https    [host] => example.com    [path] => /path    [query] => param=value)*/
// Parse query string$query = "name=John&age=25&city=New+York";parse_str($query, $params);// $params = ["name" => "John", "age" => "25", "city" => "New York"]String Templating
Section titled “String Templating”class StringTemplate {    public static function render($template, $vars) {        return preg_replace_callback('/\{\{(\w+)\}\}/', function($matches) use ($vars) {            return isset($vars[$matches[1]]) ? $vars[$matches[1]] : $matches[0];        }, $template);    }}
$template = "Hello, {{name}}! You are {{age}} years old.";$vars = ["name" => "John", "age" => 25];$result = StringTemplate::render($template, $vars);// "Hello, John! You are 25 years old."Common String Patterns
Section titled “Common String Patterns”CSV Handling
Section titled “CSV Handling”// Reading CSV data$csvLine = '"John Doe","25","Engineer","New York"';$data = str_getcsv($csvLine);// ["John Doe", "25", "Engineer", "New York"]
// Creating CSV data$data = ["John Doe", "25", "Engineer", "New York"];$csvLine = '"' . implode('","', $data) . '"';Path Operations
Section titled “Path Operations”$path = "/var/www/html/index.php";
$dirname = dirname($path); // "/var/www/html"$basename = basename($path); // "index.php"$filename = pathinfo($path, PATHINFO_FILENAME); // "index"$extension = pathinfo($path, PATHINFO_EXTENSION); // "php"
// Build path$newPath = $dirname . DIRECTORY_SEPARATOR . "config.php";JSON String Handling
Section titled “JSON String Handling”$data = ["name" => "John", "age" => 25];$json = json_encode($data); // '{"name":"John","age":25}'
$decoded = json_decode($json, true); // Back to array$object = json_decode($json); // As stdClass objectPerformance Considerations
Section titled “Performance Considerations”String Concatenation Performance
Section titled “String Concatenation Performance”// Inefficient for many concatenations$result = "";for ($i = 0; $i < 1000; $i++) {    $result .= "item $i ";}
// More efficient approach$items = [];for ($i = 0; $i < 1000; $i++) {    $items[] = "item $i";}$result = implode(" ", $items);