Php preg_replace all matches

PHP preg_replace: Replacing All Matches

The preg_replace function in PHP allows you to replace all occurrences of a pattern in a string with another value. It uses regular expressions to match the patterns.

The syntax of preg_replace is:

preg_replace(pattern, replacement, subject)
  • pattern: The regex pattern to be matched
  • replacement: The value to replace with
  • subject: The string to perform the replacement on

Example:


    // Replacing all occurrences of numbers with 'x'
    $string = "1234 Hello 5678 World";
    $pattern = "/\d+/"; // Match any digit
    $replacement = "x";
    
    $result = preg_replace($pattern, $replacement, $string);
    echo $result; // Output: "x Hello x World"
  

In the above example, the pattern /\d+/ matches any sequence of digits. The preg_replace function replaces all occurrences of this pattern with the value 'x' in the string $string.

The resulting string after the replacement is "x Hello x World".

You can use various regex patterns and replacements based on your requirements. preg_replace is a versatile function that allows you to perform complex string manipulations using regular expressions.

Leave a comment