intermediate Step 6 of 16

Strings and Regular Expressions

PHP Programming

Strings and Regular Expressions

String handling is one of PHP's strongest areas. Originally designed for generating HTML output, PHP has an extensive library of string functions and powerful regular expression support through PCRE (Perl Compatible Regular Expressions). Whether you are parsing user input, generating URLs, processing template content, or validating data formats, you will rely heavily on PHP's string capabilities. PHP distinguishes between single-quoted and double-quoted strings, with double quotes supporting variable interpolation and escape sequences.

String Functions

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

// Length and case
echo strlen($text);              // 22
echo strtoupper($text);          // "  HELLO, PHP WORLD!  "
echo strtolower($text);          // "  hello, php world!  "
echo ucfirst("hello world");     // "Hello world"
echo ucwords("hello php world"); // "Hello Php World"

// Trimming
echo trim($text);     // "Hello, PHP World!"
echo ltrim($text);    // Left trim
echo rtrim($text);    // Right trim

// Searching
echo strpos($text, "PHP");      // 9 (position)
echo strrpos($text, "l");       // 14 (last occurrence)
echo str_contains($text, "PHP"); // true (PHP 8.0+)
echo str_starts_with($text, "  H"); // true (PHP 8.0+)
echo str_ends_with($text, "!  ");   // true (PHP 8.0+)

// Extracting
echo substr($text, 9, 3);  // "PHP"
echo substr($text, -8, 5); // "World"

// Replacing
echo str_replace("World", "Developer", $text);
echo str_ireplace("php", "Python", $text);  // Case-insensitive

// Splitting and joining
$csv = "apple,banana,cherry,date";
$fruits = explode(",", $csv);     // ["apple", "banana", "cherry", "date"]
$joined = implode(" | ", $fruits); // "apple | banana | cherry | date"

// Repeating and padding
echo str_repeat("-", 40);          // "----..."
echo str_pad("42", 5, "0", STR_PAD_LEFT);  // "00042"
echo str_pad("Hi", 10, ".", STR_PAD_RIGHT); // "Hi........"

// Formatting
echo sprintf("Name: %s, Age: %d, GPA: %.2f", "Alice", 30, 3.856);
// "Name: Alice, Age: 30, GPA: 3.86"
echo number_format(1234567.89, 2, '.', ',');  // "1,234,567.89"
?>

Regular Expressions (PCRE)

<?php
// preg_match — test if pattern matches
$email = "alice@example.com";
if (preg_match('/^[^\s@]+@[^\s@]+\.[^\s@]+$/', $email)) {
    echo "Valid email
";
}

// preg_match with captures
$date = "2024-03-15";
if (preg_match('/(\d{4})-(\d{2})-(\d{2})/', $date, $matches)) {
    echo "Year: {$matches[1]}
";   // "2024"
    echo "Month: {$matches[2]}
";  // "03"
    echo "Day: {$matches[3]}
";    // "15"
}

// Named captures
preg_match('/(?P\d{4})-(?P\d{2})-(?P\d{2})/', $date, $m);
echo $m['year'];  // "2024"

// preg_match_all — find all matches
$text = "Call 555-1234 or 555-5678 today";
preg_match_all('/\d{3}-\d{4}/', $text, $matches);
print_r($matches[0]);  // ["555-1234", "555-5678"]

// preg_replace — replace with pattern
$html = "

Hello World

"; $plain = preg_replace('/<[^>]+>/', '', $html); echo $plain; // "Hello World" // Replace with callback $text = "prices: $10 and $25 and $100"; $result = preg_replace_callback('/\$(\d+)/', function($m) { return '$' . ($m[1] * 1.1); // Add 10% }, $text); echo $result; // "prices: $11 and $27.5 and $110" // preg_split — split with pattern $words = preg_split('/[\s,;]+/', "hello, world; foo bar"); print_r($words); // ["hello", "world", "foo", "bar"] ?>

Practical Validation Functions

<?php
function validateInput(string $value, string $type): bool {
    return match($type) {
        'email' => filter_var($value, FILTER_VALIDATE_EMAIL) !== false,
        'url' => filter_var($value, FILTER_VALIDATE_URL) !== false,
        'ip' => filter_var($value, FILTER_VALIDATE_IP) !== false,
        'phone' => (bool)preg_match('/^\+?[\d\s\-\(\)]{10,}$/', $value),
        'slug' => (bool)preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $value),
        'password' => strlen($value) >= 8
            && preg_match('/[A-Z]/', $value)
            && preg_match('/[a-z]/', $value)
            && preg_match('/[0-9]/', $value),
        default => !empty(trim($value))
    };
}

echo validateInput("alice@example.com", "email") ? "Valid" : "Invalid";
echo validateInput("my-cool-slug", "slug") ? "Valid" : "Invalid";
echo validateInput("Password1", "password") ? "Valid" : "Invalid";

// Sanitize input
function sanitize(string $input): string {
    $input = trim($input);
    $input = stripslashes($input);
    $input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
    return $input;
}
?>
Pro tip: PHP 8.0 introduced str_contains(), str_starts_with(), and str_ends_with() — use these instead of strpos() !== false which was the old (and error-prone) way to check if a string contains a substring. The strpos approach fails silently when the match is at position 0 because 0 == false in PHP.

Key Takeaways

  • PHP has extensive string functions: strlen(), strpos(), substr(), str_replace(), explode(), implode().
  • Use str_contains(), str_starts_with(), str_ends_with() (PHP 8.0+) for readable string checks.
  • PCRE functions (preg_match, preg_replace, preg_split) provide powerful pattern matching.
  • Use filter_var() with filter constants for validating emails, URLs, and IPs — it is more reliable than regex.
  • Always sanitize user input with htmlspecialchars() to prevent XSS attacks when outputting to HTML.