Web Analytics

PHP String Functions

Beginner~30 min read

PHP provides over 100 built-in string functions for manipulating text. In this lesson, you'll learn the most essential functions that you'll use daily in PHP development!

Output
Click Run to execute your code

String Length

strlen() - Get String Length

<?php
$text = "Hello, World!";
echo strlen($text);  // Output: 13

// Useful for validation
$password = "abc123";
if (strlen($password) < 8) {
    echo "Password too short!";
}
?>

Case Conversion

Function Description Example
strtoupper() Convert to uppercase strtoupper("hello") โ†’ "HELLO"
strtolower() Convert to lowercase strtolower("HELLO") โ†’ "hello"
ucfirst() Uppercase first character ucfirst("hello") โ†’ "Hello"
lcfirst() Lowercase first character lcfirst("HELLO") โ†’ "hELLO"
ucwords() Uppercase first char of each word ucwords("hello world") โ†’ "Hello World"
<?php
$name = "john doe";
echo ucwords($name);  // Output: John Doe

// Case-insensitive comparison
$input = "HELLO";
if (strtolower($input) === "hello") {
    echo "Match!";
}
?>

Trimming Whitespace

Function Removes From Example
trim() Both ends trim(" hi ") โ†’ "hi"
ltrim() Left side ltrim(" hi ") โ†’ "hi "
rtrim() Right side rtrim(" hi ") โ†’ " hi"
<?php
$input = "  [email protected]  \n";
$clean = trim($input);  // "[email protected]"

// Trim specific characters
$url = "https://example.com/";
echo rtrim($url, '/');  // Remove trailing slash
?>

Substring Operations

substr() - Extract Part of String

<?php
$text = "Hello, World!";

// substr(string, start, length)
echo substr($text, 0, 5);   // "Hello"
echo substr($text, 7);      // "World!" (from position 7 to end)
echo substr($text, -6);     // "World!" (last 6 characters)
echo substr($text, 0, -7);  // "Hello," (all except last 7)
?>

str_split() - Split String into Array

<?php
$text = "Hello";
$chars = str_split($text);
print_r($chars);  // ["H", "e", "l", "l", "o"]

// Split into chunks
$chunks = str_split($text, 2);
print_r($chunks);  // ["He", "ll", "o"]
?>

Search and Replace

str_replace() - Replace All Occurrences

<?php
$text = "Hello World, Hello PHP!";

// Replace all "Hello" with "Hi"
$result = str_replace("Hello", "Hi", $text);
echo $result;  // "Hi World, Hi PHP!"

// Multiple replacements
$text = "I like apples and oranges";
$result = str_replace(
    ["apples", "oranges"],
    ["bananas", "grapes"],
    $text
);
echo $result;  // "I like bananas and grapes"

// Count replacements
$count = 0;
str_replace("Hello", "Hi", $text, $count);
echo $count;  // 2
?>

str_ireplace() - Case-Insensitive Replace

<?php
$text = "Hello HELLO hello";
$result = str_ireplace("hello", "Hi", $text);
echo $result;  // "Hi Hi Hi"
?>

Finding Substrings

Function Returns Case-Sensitive
strpos() Position of first occurrence Yes
stripos() Position of first occurrence No
strrpos() Position of last occurrence Yes
strstr() String from first occurrence Yes
<?php
$text = "Hello World";

// Find position
$pos = strpos($text, "World");
echo $pos;  // 6

// Check if substring exists
if (strpos($text, "World") !== false) {
    echo "Found!";
}

// Get substring from position
$result = strstr($text, "World");
echo $result;  // "World"
?>
Important: Always use !== false when checking strpos(). If the substring is at position 0, it returns 0 which is falsy!

String to Array Conversion

explode() - Split String by Delimiter

<?php
$csv = "John,Doe,30,Engineer";
$parts = explode(",", $csv);
print_r($parts);
// ["John", "Doe", "30", "Engineer"]

// Limit splits
$limited = explode(",", $csv, 2);
print_r($limited);
// ["John", "Doe,30,Engineer"]
?>

implode() - Join Array into String

<?php
$words = ["Hello", "World", "PHP"];
$sentence = implode(" ", $words);
echo $sentence;  // "Hello World PHP"

// Also called join()
$csv = join(",", $words);
echo $csv;  // "Hello,World,PHP"
?>

String Comparison

Function Description Returns
strcmp() Binary safe comparison <0, 0, or >0
strcasecmp() Case-insensitive comparison <0, 0, or >0
strncmp() Compare first n characters <0, 0, or >0
<?php
$str1 = "apple";
$str2 = "Apple";

echo strcmp($str1, $str2);      // > 0 (different)
echo strcasecmp($str1, $str2);  // 0 (same, ignoring case)
?>

Other Useful Functions

str_repeat() - Repeat String

<?php
echo str_repeat("*", 10);  // "**********"
echo str_repeat("Ha", 3);  // "HaHaHa"
?>

str_pad() - Pad String

<?php
$num = "42";
echo str_pad($num, 5, "0", STR_PAD_LEFT);   // "00042"
echo str_pad($num, 5, "0", STR_PAD_RIGHT);  // "42000"
echo str_pad($num, 6, "-", STR_PAD_BOTH);   // "--42--"
?>

str_word_count() - Count Words

<?php
$text = "Hello World PHP";
echo str_word_count($text);  // 3

// Get array of words
$words = str_word_count($text, 1);
print_r($words);  // ["Hello", "World", "PHP"]
?>

strrev() - Reverse String

<?php
echo strrev("Hello");  // "olleH"
?>

Common Mistakes

1. Using == instead of === with strpos()

<?php
$text = "Hello World";

if (strpos($text, "Hello") == false) {  // โŒ Wrong!
    // This executes because strpos returns 0 (position)
    // and 0 == false is true
}

if (strpos($text, "Hello") === false) {  // โœ… Correct
    // This won't execute
}
?>

2. Confusing substr() parameters

<?php
$text = "Hello World";

// Wrong parameter order
substr($text, 5, 0);  // โŒ Empty string

// Correct
substr($text, 0, 5);  // โœ… "Hello"
?>

Summary

  • Length: strlen()
  • Case: strtoupper(), strtolower(), ucwords()
  • Trim: trim(), ltrim(), rtrim()
  • Substring: substr(), str_split()
  • Replace: str_replace(), str_ireplace()
  • Find: strpos(), strstr()
  • Array: explode(), implode()
  • Compare: strcmp(), strcasecmp()

What's Next?

You've mastered strings! Now let's learn about Constants - values that never change throughout your program's execution. Perfect for configuration values, API keys, and more!