Skip to content
PHP

String Functions in PHP

Manipulate strings with substr, replace, explode, and sprintf in PHP.

By EZ4Code Team
stringbeginner

Code

<?php

$str = "Hello, World";

// Length and case
echo strlen($str);          // 12
echo strtoupper($str);      // HELLO, WORLD
echo strtolower($str);

// Substring and replace
echo substr($str, 0, 5);    // Hello
echo str_replace("World", "PHP", $str);

// Search
$pos = strpos($str, "World");
if ($pos !== false) {
    echo "Found at $pos";
}

// Split and join
$parts = explode(", ", $str);
$joined = implode(" | ", $parts);

// Format
$formatted = sprintf("Name: %s, Age: %d", "Alice", 30);

// Trim
echo trim("  hello  ");     // hello

Explanation

Covers common string operations: strlen for length, strtoupper/lower for case, substr for extraction, and str_replace for substitution. strpos returns false when not found, so always compare with !== (not !=). explode/implode split and join strings, and sprintf formats with type specifiers.

More PHP Snippets