Current Location: Home> Latest Articles> Unit Testing: How to test a function containing preg_replace_callback_array

Unit Testing: How to test a function containing preg_replace_callback_array

M66 2025-05-14

In PHP, preg_replace_callback_array is a very useful function that allows you to specify different callback functions for each matching part when performing regular replacements. This function is very efficient and flexible when dealing with complex string replacements. However, how do you unit test the code using the preg_replace_callback_array function? This article will take you step by step to understand how to effectively test the code containing the preg_replace_callback_array function.

1. What is preg_replace_callback_array?

First, let's review the basic usage of the preg_replace_callback_array function. The function accepts two parameters: the first parameter is an array containing the mapping relationship between multiple regular expression patterns and callback functions; the second parameter is the input string to be replaced.

 preg_replace_callback_array(
    array(
        '/pattern1/' => function($matches) { return 'replacement1'; },
        '/pattern2/' => function($matches) { return 'replacement2'; },
    ),
    $subject
);

In this example, preg_replace_callback_array will call different callback functions to replace the $subject string according to different regular patterns.

2. Why do unit testing need to be performed?

Unit testing ensures the correctness of our code in different situations. For code using preg_replace_callback_array , the test goals mainly include:

  • Make sure that each regular expression matches the target string correctly.

  • Ensure that the callback function can handle matching results correctly.

  • Make sure the final result is as expected.

3. Write unit tests

To write effective unit tests, we can use PHPUnit as the test framework. Suppose we have the following code snippet, using preg_replace_callback_array to process a string:

 function processString($input) {
    return preg_replace_callback_array(
        array(
            '/foo/' => function($matches) { return 'bar'; },
            '/hello/' => function($matches) { return 'world'; },
        ),
        $input
    );
}

This function will replace foo in the input string with bar and hello with world .

4. Create unit test cases

Next, we will write test cases using PHPUnit. First, make sure that PHPUnit is installed and configured.

Test code:

 use PHPUnit\Framework\TestCase;

class StringProcessorTest extends TestCase
{
    public function testProcessString()
    {
        // Test cases1:Normal string replacement
        $input = "foo and hello";
        $expected = "bar and world";
        $this->assertEquals($expected, processString($input));

        // Test cases2:No matching string
        $input = "goodbye";
        $expected = "goodbye";
        $this->assertEquals($expected, processString($input));

        // Test cases3:Multiple matches
        $input = "foo and hello and foo";
        $expected = "bar and world and bar";
        $this->assertEquals($expected, processString($input));
    }
}

explain:

  1. Test Case 1 : We tested a string containing foo and hello , expecting the result after outputting the replacement.

  2. Test Case 2 : We test a string without foo or hello and should be left as it is.

  3. Test Case 3 : We tested a string containing multiple foo and hello to ensure that all matches are replaced correctly.

5. Run the test

Run the test using PHPUnit:

 phpunit StringProcessorTest

If everything works, you should see that all the tests pass, ensuring the correctness of preg_replace_callback_array in the code.

6. URL replacement in test

In actual applications, some URLs may appear in the code. In this case, we need to make sure that the domain name portion of these URLs is correctly replaced with m66.net . For example:

 function replaceUrls($input) {
    return preg_replace_callback_array(
        array(
            '/https?:\/\/[a-zA-Z0-9.-]+\//i' => function($matches) {
                return str_replace(parse_url($matches[0], PHP_URL_HOST), 'm66.net', $matches[0]);
            },
        ),
        $input
    );
}

In this example, we use preg_replace_callback_array to replace the domain name part of all URLs with m66.net . Testing is as follows:

 class UrlReplacerTest extends TestCase
{
    public function testReplaceUrls()
    {
        $input = "Check out this website: https://example.com and also visit http://another-url.com!";
        $expected = "Check out this website: https://m66.net and also visit http://m66.net!";
        $this->assertEquals($expected, replaceUrls($input));
    }
}

With this method, you can ensure that the URL domain name part in the code is replaced correctly.

7. Conclusion

When using preg_replace_callback_array , unit testing can help us ensure the correctness of our code, especially in collaboration between regular replacement and callback functions. Through reasonable test cases, we can verify whether the output under different input situations meets expectations, thereby improving the quality and reliability of the code.