How can regular expressions be used in PHP to make the implementation of a 301 redirect easier?

Regular expressions can be used in PHP to match and redirect multiple URLs with similar patterns using a single rule. This can make the implementation of a 301 redirect easier by reducing the number of individual redirect rules that need to be written. By using regular expressions to match patterns in URLs, you can create a more flexible and efficient redirect system.

// Redirect URLs with a similar pattern using regular expressions
$oldUrls = array(
    '/old-url-1/',
    '/old-url-2/',
    '/old-url-3/'
);

$newUrl = '/new-url/';

foreach ($oldUrls as $oldUrl) {
    if (preg_match('#^' . $oldUrl . '#', $_SERVER['REQUEST_URI'])) {
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: ' . $newUrl);
        exit();
    }
}