[PHP] How to find a specific pattern in a string and replace it with a new pattern?

| | 1 min read

Have you ever encountered a situation where you have to find a specific pattern in a string and had to replace it with a new pattern in PHP. You will often encounter such situations during web development or any type of programming. Read on to know how to find a specific pattern in a string and replace it with a new pattern using PHP.

The actual method

  • We can accomplish this using the PHP preg_replace_callback function.
  • Using this function we have to locate the matching pattern first
  • Next we pass matched string as a parameter to a callback function.
  • This custom callback function will replace the old pattern with the new pattern and return it to the string.
  • Lets look at an example
    Here is our test string. It is an HTML markup which we need to replace.
    // Test string
    $string = "<div style='width:200px;height:100px;'>One</div><div style='font-size:20px;margin:100px;'>two</div><div style='left:200px;padding:100px;'>Three</div>";
  • Now onto the preg_replace_callback function. Checkout the format below.
    // Function to replace the string. Here we are trying to match width:number
    $newStr = preg_replace_callback("!width:\d+!", "customconvert", $string);
  • Here is the custom call back function
    // Callback function.
    function customconvert($match) {
    // To show matched string.
    print_r($match);
    $word = explode(':', $match[0]);
    // Here I am increasing the width by 20% then returning the string.
    return $word[0] .":". $word[1] * 1.2;
    }

Hope that was helpful. Fire your feedbacks using the comment form below