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 "); // helloExplanation
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
Arrays and Array Functions in PHP
Create indexed, associative, and multidimensional arrays with map and filter.
Read and Write Files in PHP
Read, write, append, and iterate files with PHP filesystem functions.
PDO Database Queries in PHP
Connect and run prepared statements safely with PDO in PHP.
Sessions and Cookies in PHP
Store user data across requests with sessions and cookies in PHP.
Classes and Inheritance in PHP
Define classes with constructors, visibility, and inheritance in PHP.