← Back to Chapters

PHP preg_replace() & preg_split()

? PHP preg_replace() & preg_split()

? Quick Overview

The preg_replace() and preg_split() functions in PHP are powerful tools for manipulating strings using regular expressions. preg_replace() replaces matching patterns, while preg_split() breaks strings into arrays based on patterns.

? Key Concepts

  • Regular Expressions define flexible search patterns
  • preg_replace() performs pattern-based replacement
  • preg_split() performs pattern-based splitting

? Syntax / Theory

  • preg_replace(pattern, replacement, subject)
  • preg_split(pattern, subject)

? Code Example

? View Code Example
// Using preg_replace() and preg_split()
<?php
$text = "The quick brown fox jumps over the lazy dog.";
$pattern = "/quick/";
$replacement = "fast";
$new_text = preg_replace($pattern, $replacement, $text);
echo "After replacement: " . $new_text . "<br>";

$string = "apple,banana,grape,orange";
$split_pattern = "/,/";
$fruits = preg_split($split_pattern, $string);
print_r($fruits);
?>

? Live Output / Explanation

Output Explanation:

  • The word quick is replaced with fast
  • The comma-separated string becomes an array of fruits

? Interactive Concept

Think of preg_replace() as a find-and-replace engine and preg_split() as smart scissors that cut text wherever the pattern matches.

? Use Cases

  • Sanitizing user input
  • Formatting text dynamically
  • Tokenizing CSV or log data

✅ Tips & Best Practices

  • Always test regex patterns before production use
  • Use modifiers like i for case-insensitive matching
  • Keep patterns simple for performance

? Try It Yourself

  • Replace multiple words using one pattern
  • Split a sentence into individual words
  • Clean and validate an email using regex