πŸ”§ PHP String Functions Reference

Parent: Strings PHP Index


Complete Function Reference

FunctionDescriptionExample
strlen($s)Byte lengthstrlen("hi") β†’ 2
mb_strlen($s)Character length (UTF-8)mb_strlen("hΓ©llo") β†’ 5
strpos($s,$n)First positionstrpos("hello","l") β†’ 2
strrpos($s,$n)Last positionstrrpos("hello","l") β†’ 3
stripos($s,$n)First, case-insensitivestripos("Hello","h") β†’ 0
substr($s,s,l)Substringsubstr("hello",1,3) β†’ "ell"
str_contains($s,$n)Contains? (PHP 8)str_contains("hello","ell") β†’ true
str_starts_with($s,$n)Prefix? (PHP 8)str_starts_with("hello","he") β†’ true
str_ends_with($s,$n)Suffix? (PHP 8)str_ends_with("hello","lo") β†’ true
strtolower($s)Lowercasestrtolower("HI") β†’ "hi"
strtoupper($s)Uppercasestrtoupper("hi") β†’ "HI"
ucfirst($s)Capitalize firstucfirst("hello") β†’ "Hello"
ucwords($s)Capitalize each worducwords("hello world") β†’ "Hello World"
trim($s)Remove whitespacetrim(" hi ") β†’ "hi"
ltrim($s)Trim left
rtrim($s)Trim right
str_replace($n,$r,$s)Replace allstr_replace("l","L","hello") β†’ "heLLo"
str_ireplaceReplace, case-insensitive
str_pad($s,$l,$p)Pad to lengthstr_pad("5",3,"0",STR_PAD_LEFT) β†’ "005"
str_repeat($s,$n)Repeatstr_repeat("ab",3) β†’ "ababab"
strrev($s)Reversestrrev("hello") β†’ "olleh"
str_split($s,$l)Split to chars/chunksstr_split("hi") β†’ ['h','i']
explode($d,$s)Split by delimiterexplode(",","a,b") β†’ ['a','b']
implode($d,$a)Join arrayimplode(",",['a','b']) β†’ "a,b"
sprintf($f,...)Format stringsprintf("%05d", 7) β†’ "00007"
number_format($n)Format numbernumber_format(1234.5,2) β†’ "1,234.50"
ord($c)Char to ASCIIord('A') β†’ 65
chr($n)ASCII to charchr(65) β†’ "A"
strcmp($a,$b)Compare (case-sensitive)Returns <0, 0, >0
strcasecmp($a,$b)Compare (case-insensitive)
substr_count($s,$n)Count occurrencessubstr_count("hello","l") β†’ 2
str_word_count($s)Count wordsstr_word_count("Hi there") β†’ 2
nl2br($s)Newlines to <br>
htmlspecialchars($s)Escape HTMLPrevents XSS
preg_match($p,$s,&$m)Match regexReturns 1/0
preg_match_all($p,$s,&$m)Match allReturns count
preg_replace($p,$r,$s)Regex replace
preg_split($p,$s)Regex split

Q1. Check If Pangram

Problem: Does string contain every letter a-z?


🧠 How to Approach This

Step 1 β€” Recognize: Pangram = all 26 letters present.

Step 2 β€” Approach: Count distinct lowercase letters. If >= 26 β†’ pangram.

function checkIfPangram(string $s): bool {
    $seen = [];
    foreach (str_split(strtolower($s)) as $c) {
        if ($c >= 'a' && $c <= 'z') $seen[$c] = true;
    }
    return count($seen) === 26;
}

echo checkIfPangram("The quick brown fox jumps over the lazy dog") ? 'yes' : 'no'; // yes

Time: O(n) | Space: O(1)


Q2. Count Vowels and Consonants

function countVowelsConsonants(string $s): array {
    $s = strtolower($s);
    $vowels = 0; $consonants = 0;
    foreach (str_split($s) as $c) {
        if (strpos('aeiou', $c) !== false) $vowels++;
        elseif ($c >= 'a' && $c <= 'z')   $consonants++;
    }
    return ['vowels' => $vowels, 'consonants' => $consonants];
}

print_r(countVowelsConsonants("Hello World"));
// vowels: 3, consonants: 7

Q3. Most Frequent Character

function mostFrequent(string $s): string {
    $freq = [];
    foreach (str_split($s) as $c) $freq[$c] = ($freq[$c] ?? 0) + 1;
    arsort($freq);
    return array_key_first($freq);
}

echo mostFrequent("aabbbcc"); // 'b'

Q4. Remove Duplicates (Preserve Order)

function removeDuplicates(string $s): string {
    $seen = [];
    $result = '';
    foreach (str_split($s) as $c) {
        if (!isset($seen[$c])) { $seen[$c] = true; $result .= $c; }
    }
    return $result;
}

echo removeDuplicates("programming"); // "progamin"

Q5. Reverse Words in Sentence

function reverseWords(string $s): string {
    $words = preg_split('/\s+/', trim($s));
    return implode(' ', array_reverse($words));
}

echo reverseWords("Hello World PHP"); // "PHP World Hello"

Q6. Caesar Cipher

function caesarCipher(string $s, int $shift): string {
    $result = '';
    foreach (str_split($s) as $c) {
        if ($c >= 'a' && $c <= 'z') {
            $result .= chr((ord($c) - ord('a') + $shift) % 26 + ord('a'));
        } elseif ($c >= 'A' && $c <= 'Z') {
            $result .= chr((ord($c) - ord('A') + $shift) % 26 + ord('A'));
        } else {
            $result .= $c;
        }
    }
    return $result;
}

echo caesarCipher("Hello", 3); // "Khoor"
echo caesarCipher("Khoor", 23); // "Hello" (decrypt)

Q7. Check Balanced Brackets

function isBalanced(string $s): bool {
    $stack = [];
    $map = [')'=>'(', ']'=>'[', '}'=>'{'];
    foreach (str_split($s) as $c) {
        if (in_array($c, ['(','[','{'])) {
            $stack[] = $c;
        } elseif (isset($map[$c])) {
            if (empty($stack) || array_pop($stack) !== $map[$c]) return false;
        }
    }
    return empty($stack);
}

echo isBalanced("({[]})") ? 'yes' : 'no'; // yes
echo isBalanced("([)]")   ? 'yes' : 'no'; // no

Q8. First Non-Repeating Character


🧠 How to Approach This

Step 1: Count frequencies. Then scan left-to-right for first char with count == 1.

function firstUniqChar(string $s): int {
    $freq = array_fill(0, 26, 0);
    for ($i = 0; $i < strlen($s); $i++)
        $freq[ord($s[$i]) - ord('a')]++;

    for ($i = 0; $i < strlen($s); $i++)
        if ($freq[ord($s[$i]) - ord('a')] === 1) return $i;

    return -1;
}

echo firstUniqChar("leetcode"); // 0
echo firstUniqChar("aabb");     // -1

Time: O(n) | Space: O(1)


Q9. String Compression

Problem: "aaabbc" β†’ "a3b2c1" (if compressed is shorter, return it; else return original)


🧠 How to Approach This

Step 1: Walk string, count consecutive chars. Build result. Compare lengths.

function compressString(string $s): string {
    if (strlen($s) === 0) return $s;
    $result = '';
    $count  = 1;
    for ($i = 1; $i < strlen($s); $i++) {
        if ($s[$i] === $s[$i-1]) { $count++; continue; }
        $result .= $s[$i-1] . $count;
        $count = 1;
    }
    $result .= $s[strlen($s)-1] . $count;
    return strlen($result) < strlen($s) ? $result : $s;
}

echo compressString("aabcccccaaa"); // "a2b1c5a3"
echo compressString("abc");        // "abc" (no compression gain)

Time: O(n) | Space: O(n)


Q10. Format with sprintf

// Zero-pad numbers
sprintf("%05d", 42);        // "00042"
sprintf("%.2f", 3.14159);  // "3.14"
sprintf("%s has %d items", "Cart", 3); // "Cart has 3 items"

// Practical: format money
function formatMoney(float $amount): string {
    return '$' . number_format($amount, 2);
}
echo formatMoney(1234.5); // "$1,234.50"

Regex Quick Reference

// Common patterns
'/^\d+$/'         // digits only
'/^[a-zA-Z]+$/'  // letters only
'/\b\w+\b/'      // words
'/[\w\.-]+@[\w\.-]+\.\w+/' // email (simple)

// Email validation
function isValidEmail(string $email): bool {
    return (bool) filter_var($email, FILTER_VALIDATE_EMAIL);
}

// Extract numbers
preg_match_all('/\d+/', "abc123def456", $m);
print_r($m[0]); // ['123', '456']

// Named groups
preg_match('/(?P<year>\d{4})-(?P<month>\d{2})/', '2024-01', $m);
echo $m['year'];  // "2024"
echo $m['month']; // "01"