1. php
  2. /references
  3. /string-functions

String Functions Reference

Introduction to PHP String Functions

PHP provides a rich set of built-in string functions for manipulating, searching, formatting, and validating strings. This reference covers the most commonly used string functions with practical examples.

String Length and Information

strlen() - Get String Length

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

$unicode = "Hello 世界";
echo strlen($unicode); // Output: 12 (bytes, not characters)
echo mb_strlen($unicode, 'UTF-8'); // Output: 8 (characters)

// Check if string is empty
function isEmptyString($str) {
    return strlen(trim($str)) === 0;
}

echo isEmptyString("   ") ? "Empty" : "Not empty"; // Output: Empty
?>

str_word_count() - Count Words

<?php
$text = "The quick brown fox jumps over the lazy dog";

// Count words
echo str_word_count($text); // Output: 9

// Get array of words
$words = str_word_count($text, 1);
print_r($words);
/* Output:
Array (
    [0] => The
    [1] => quick
    [2] => brown
    [3] => fox
    [4] => jumps
    [5] => over
    [6] => the
    [7] => lazy
    [8] => dog
)
*/

// Get word positions
$positions = str_word_count($text, 2);
print_r($positions);
/* Output:
Array (
    [0] => The
    [4] => quick
    [10] => brown
    [16] => fox
    [20] => jumps
    [26] => over
    [31] => the
    [35] => lazy
    [40] => dog
)
*/
?>

String Searching and Finding

strpos() - Find Position of Substring

<?php
$haystack = "The quick brown fox jumps over the lazy dog";
$needle = "brown";

$position = strpos($haystack, $needle);
if ($position !== false) {
    echo "Found '$needle' at position $position"; // Output: Found 'brown' at position 10
} else {
    echo "'$needle' not found";
}

// Case-insensitive search
$position = stripos($haystack, "BROWN");
echo $position; // Output: 10

// Find last occurrence
$position = strrpos($haystack, "the");
echo $position; // Output: 31

// Find first occurrence of any character from a set
$position = strpbrk($haystack, "aeiou");
echo $position; // Output: e quick brown fox jumps over the lazy dog
?>

str_contains() - Check if String Contains Substring (PHP 8+)

<?php
$text = "The quick brown fox";

if (str_contains($text, "brown")) {
    echo "Contains 'brown'"; // Output: Contains 'brown'
}

if (str_starts_with($text, "The")) {
    echo "Starts with 'The'"; // Output: Starts with 'The'
}

if (str_ends_with($text, "fox")) {
    echo "Ends with 'fox'"; // Output: Ends with 'fox'
}

// For older PHP versions
function contains($haystack, $needle) {
    return strpos($haystack, $needle) !== false;
}

function startsWith($haystack, $needle) {
    return strpos($haystack, $needle) === 0;
}

function endsWith($haystack, $needle) {
    return substr($haystack, -strlen($needle)) === $needle;
}
?>

String Manipulation

substr() - Extract Substring

<?php
$text = "Hello World";

// Extract from position 6
echo substr($text, 6); // Output: World

// Extract 5 characters from position 0
echo substr($text, 0, 5); // Output: Hello

// Extract from end
echo substr($text, -5); // Output: World

// Extract from position with negative length
echo substr($text, 0, -6); // Output: Hello

// Safe substring function
function safeSubstr($string, $start, $length = null) {
    if ($start < 0) {
        $start = max(0, strlen($string) + $start);
    }
    
    if ($length === null) {
        return substr($string, $start);
    }
    
    return substr($string, $start, $length);
}

echo safeSubstr("Hello", 10); // Output: (empty string)
?>

str_replace() - Replace Substrings

<?php
$text = "The quick brown fox jumps over the lazy dog";

// Simple replacement
$newText = str_replace("fox", "cat", $text);
echo $newText; // Output: The quick brown cat jumps over the lazy dog

// Multiple replacements
$search = ["quick", "brown", "lazy"];
$replace = ["slow", "red", "active"];
$newText = str_replace($search, $replace, $text);
echo $newText; // Output: The slow red fox jumps over the active dog

// Case-insensitive replacement
$newText = str_ireplace("QUICK", "slow", $text);
echo $newText; // Output: The slow brown fox jumps over the lazy dog

// Count replacements
$count = 0;
$newText = str_replace("the", "a", $text, $count);
echo "Replaced $count occurrences"; // Output: Replaced 2 occurrences

// Advanced replacement function
function replaceWords($text, $replacements) {
    $pattern = '/\b(' . implode('|', array_keys($replacements)) . ')\b/i';
    return preg_replace_callback($pattern, function($matches) use ($replacements) {
        $word = strtolower($matches[1]);
        return $replacements[$word] ?? $matches[1];
    }, $text);
}

$replacements = [
    'quick' => 'fast',
    'brown' => 'red',
    'fox' => 'cat'
];
echo replaceWords($text, $replacements);
?>

trim() - Remove Whitespace

<?php
$text = "  Hello World  ";

// Remove whitespace from both ends
echo "'" . trim($text) . "'"; // Output: 'Hello World'

// Remove from left only
echo "'" . ltrim($text) . "'"; // Output: 'Hello World  '

// Remove from right only
echo "'" . rtrim($text) . "'"; // Output: '  Hello World'

// Remove specific characters
$text = "...Hello World...";
echo trim($text, '.'); // Output: Hello World

// Remove multiple characters
$text = " \t\n Hello World \t\n ";
echo "'" . trim($text) . "'"; // Output: 'Hello World'

// Custom trim function
function smartTrim($string, $chars = " \t\n\r\0\x0B") {
    return trim($string, $chars);
}

// Remove quotes
$quoted = '"Hello World"';
echo trim($quoted, '"'); // Output: Hello World
?>

Case Conversion

strtoupper() / strtolower() - Change Case

<?php
$text = "Hello World";

// Convert to uppercase
echo strtoupper($text); // Output: HELLO WORLD

// Convert to lowercase
echo strtolower($text); // Output: hello world

// Capitalize first letter
echo ucfirst($text); // Output: Hello World

// Capitalize first letter of each word
echo ucwords($text); // Output: Hello World

// Capitalize words with custom delimiters
echo ucwords("hello-world", "-"); // Output: Hello-World

// Custom title case function
function titleCase($string) {
    $smallWords = ['a', 'an', 'and', 'as', 'at', 'but', 'by', 'for', 'if', 'in', 'of', 'on', 'or', 'the', 'to', 'up'];
    
    $words = explode(' ', strtolower($string));
    
    foreach ($words as $key => $word) {
        if ($key === 0 || $key === count($words) - 1 || !in_array($word, $smallWords)) {
            $words[$key] = ucfirst($word);
        }
    }
    
    return implode(' ', $words);
}

echo titleCase("the quick brown fox"); // Output: The Quick Brown Fox

// Multibyte case conversion (for Unicode)
$unicode = "héllo wörld";
echo mb_strtoupper($unicode); // Output: HÉLLO WÖRLD
echo mb_strtolower($unicode); // Output: héllo wörld
?>

String Splitting and Joining

explode() / implode() - Split and Join

<?php
// Split string into array
$text = "apple,banana,orange,grape";
$fruits = explode(",", $text);
print_r($fruits);
/* Output:
Array (
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)
*/

// Limit splits
$fruits = explode(",", $text, 2);
print_r($fruits);
/* Output:
Array (
    [0] => apple
    [1] => banana,orange,grape
)
*/

// Join array into string
$fruits = ["apple", "banana", "orange"];
echo implode(", ", $fruits); // Output: apple, banana, orange

// Alternative: join() is alias of implode()
echo join(" | ", $fruits); // Output: apple | banana | orange

// Split by multiple delimiters
function multiExplode($delimiters, $string) {
    $pattern = '/[' . preg_quote(implode('', $delimiters), '/') . ']/';
    return preg_split($pattern, $string);
}

$text = "apple,banana;orange|grape";
$fruits = multiExplode([',', ';', '|'], $text);
print_r($fruits);

// Smart CSV parsing
function parseCSV($line, $delimiter = ',', $enclosure = '"') {
    $fields = [];
    $field = '';
    $inEnclosure = false;
    $len = strlen($line);
    
    for ($i = 0; $i < $len; $i++) {
        $char = $line[$i];
        
        if ($char === $enclosure) {
            $inEnclosure = !$inEnclosure;
        } elseif ($char === $delimiter && !$inEnclosure) {
            $fields[] = $field;
            $field = '';
        } else {
            $field .= $char;
        }
    }
    
    $fields[] = $field;
    return $fields;
}

$csvLine = '"John Doe","25","New York, NY"';
$fields = parseCSV($csvLine);
print_r($fields);
?>

String Padding and Alignment

str_pad() - Pad String

<?php
$text = "Hello";

// Pad to 10 characters (right padding)
echo str_pad($text, 10); // Output: "Hello     "

// Pad to 10 characters (left padding)
echo str_pad($text, 10, " ", STR_PAD_LEFT); // Output: "     Hello"

// Pad to 10 characters (both sides)
echo str_pad($text, 10, " ", STR_PAD_BOTH); // Output: "  Hello   "

// Pad with custom character
echo str_pad($text, 10, "*", STR_PAD_LEFT); // Output: "*****Hello"

// Pad with multiple characters
echo str_pad($text, 15, ".-", STR_PAD_BOTH); // Output: ".-.-Hello.-.-."

// Number padding
function padNumber($number, $length = 3) {
    return str_pad($number, $length, "0", STR_PAD_LEFT);
}

echo padNumber(5); // Output: 005
echo padNumber(42); // Output: 042
echo padNumber(123); // Output: 123

// Format price
function formatPrice($price) {
    return '$' . number_format($price, 2);
}

echo formatPrice(1234.5); // Output: $1,234.50
?>

String Formatting

sprintf() - Format String

<?php
// Basic formatting
$name = "John";
$age = 25;
echo sprintf("My name is %s and I am %d years old", $name, $age);
// Output: My name is John and I am 25 years old

// Number formatting
$price = 1234.567;
echo sprintf("Price: $%.2f", $price); // Output: Price: $1234.57

// Padding with sprintf
echo sprintf("%05d", 42); // Output: 00042
echo sprintf("%-10s", "Hello"); // Output: "Hello     "

// Multiple values
echo sprintf("%s costs $%.2f and weighs %.1f kg", "Apple", 0.5, 0.2);
// Output: Apple costs $0.50 and weighs 0.2 kg

// Date formatting
$date = new DateTime();
echo sprintf("Today is %s", $date->format('Y-m-d')); // Output: Today is 2023-01-01

// Custom formatting function
function formatBytes($size, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    
    for ($i = 0; $size >= 1024 && $i < count($units) - 1; $i++) {
        $size /= 1024;
    }
    
    return sprintf("%.{$precision}f %s", $size, $units[$i]);
}

echo formatBytes(1536); // Output: 1.50 KB
echo formatBytes(1048576); // Output: 1.00 MB

// Template system
function simpleTemplate($template, $vars) {
    return preg_replace_callback('/\{(\w+)\}/', function($matches) use ($vars) {
        return $vars[$matches[1]] ?? $matches[0];
    }, $template);
}

$template = "Hello {name}, you have {count} messages.";
$vars = ['name' => 'John', 'count' => 5];
echo simpleTemplate($template, $vars); // Output: Hello John, you have 5 messages.
?>

String Comparison

strcmp() - Compare Strings

<?php
$str1 = "apple";
$str2 = "banana";

// Binary safe string comparison
$result = strcmp($str1, $str2);
echo $result; // Output: negative number (apple < banana)

// Case-insensitive comparison
$result = strcasecmp("Apple", "APPLE");
echo $result; // Output: 0 (equal)

// Natural order comparison
$files = ["file1.txt", "file10.txt", "file2.txt"];
usort($files, 'strnatcmp');
print_r($files); // Output: file1.txt, file2.txt, file10.txt

// Version comparison
echo version_compare("1.2.3", "1.2.4"); // Output: -1

// Levenshtein distance (edit distance)
$word1 = "kitten";
$word2 = "sitting";
echo levenshtein($word1, $word2); // Output: 3

// Similar text percentage
$text1 = "Hello World";
$text2 = "Hello Word";
similar_text($text1, $text2, $percent);
echo "Similarity: " . round($percent, 2) . "%"; // Output: Similarity: 90.91%

// Soundex comparison (phonetic similarity)
echo soundex("Smith"); // Output: S530
echo soundex("Smyth"); // Output: S530

function isSimilarSounding($word1, $word2) {
    return soundex($word1) === soundex($word2);
}

echo isSimilarSounding("Smith", "Smyth") ? "Similar" : "Different"; // Output: Similar
?>

String Validation

Validation Functions

<?php
// Email validation
function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

echo isValidEmail("[email protected]") ? "Valid" : "Invalid"; // Output: Valid

// URL validation
function isValidURL($url) {
    return filter_var($url, FILTER_VALIDATE_URL) !== false;
}

echo isValidURL("https://example.com") ? "Valid" : "Invalid"; // Output: Valid

// Check if string is numeric
function isNumericString($str) {
    return is_numeric($str);
}

echo isNumericString("123.45") ? "Numeric" : "Not numeric"; // Output: Numeric

// Check if string contains only alphabetic characters
function isAlpha($str) {
    return ctype_alpha($str);
}

echo isAlpha("HelloWorld") ? "Alphabetic" : "Not alphabetic"; // Output: Alphabetic

// Check if string contains only alphanumeric characters
function isAlphanumeric($str) {
    return ctype_alnum($str);
}

echo isAlphanumeric("Hello123") ? "Alphanumeric" : "Not alphanumeric"; // Output: Alphanumeric

// Custom validation function
function validatePassword($password) {
    $errors = [];
    
    if (strlen($password) < 8) {
        $errors[] = "Password must be at least 8 characters long";
    }
    
    if (!preg_match('/[A-Z]/', $password)) {
        $errors[] = "Password must contain at least one uppercase letter";
    }
    
    if (!preg_match('/[a-z]/', $password)) {
        $errors[] = "Password must contain at least one lowercase letter";
    }
    
    if (!preg_match('/[0-9]/', $password)) {
        $errors[] = "Password must contain at least one number";
    }
    
    if (!preg_match('/[^A-Za-z0-9]/', $password)) {
        $errors[] = "Password must contain at least one special character";
    }
    
    return empty($errors) ? true : $errors;
}

$result = validatePassword("MyPass123!");
echo is_array($result) ? implode(", ", $result) : "Valid password";
?>

Advanced String Operations

String Encoding and Escaping

<?php
// HTML encoding
$text = "<script>alert('XSS')</script>";
echo htmlspecialchars($text); // Output: &lt;script&gt;alert('XSS')&lt;/script&gt;

// URL encoding
$text = "Hello World!";
echo urlencode($text); // Output: Hello+World%21
echo rawurlencode($text); // Output: Hello%20World%21

// Base64 encoding
$text = "Hello World";
$encoded = base64_encode($text);
echo $encoded; // Output: SGVsbG8gV29ybGQ=
echo base64_decode($encoded); // Output: Hello World

// JSON encoding
$data = ["name" => "John", "age" => 30];
echo json_encode($data); // Output: {"name":"John","age":30}

// Escape for SQL (basic example - use prepared statements in practice)
function escapeSql($string) {
    return str_replace("'", "''", $string);
}

// Escape for shell command
$command = "echo " . escapeshellarg($text);

// Remove HTML tags
$html = "<p>This is <strong>bold</strong> text</p>";
echo strip_tags($html); // Output: This is bold text
echo strip_tags($html, '<strong>'); // Output: This is <strong>bold</strong> text

// Convert special characters
$text = "café naïve résumé";
echo htmlentities($text, ENT_QUOTES, 'UTF-8'); 
// Output: caf&eacute; na&iuml;ve r&eacute;sum&eacute;
?>

String Hashing and Checksums

<?php
$text = "Hello World";

// MD5 hash
echo md5($text); // Output: b10a8db164e0754105b7a99be72e3fe5

// SHA1 hash
echo sha1($text); // Output: 0a4d55a8d778e5022fab701977c5d840bbc486d0

// SHA256 hash
echo hash('sha256', $text);

// Password hashing (secure)
$password = "mypassword";
$hash = password_hash($password, PASSWORD_DEFAULT);
echo $hash;

// Verify password
$isValid = password_verify($password, $hash);
echo $isValid ? "Valid" : "Invalid";

// CRC32 checksum
echo crc32($text); // Output: 222957957

// Custom hash function for short IDs
function generateShortId($input, $length = 8) {
    return substr(base_convert(md5($input), 16, 36), 0, $length);
}

echo generateShortId("Hello World"); // Output: 9ql8xmqm
?>

This comprehensive reference covers the most essential PHP string functions with practical examples for real-world development scenarios.