Skip to content
Advertisement

Altering .htaccess with PHP – removing a rewrite rule

I am using PHP to remove/add static pages once a page has been deleted, I want to be able to remove it from the .htaccess, however I’ve tried this, but it throws an error:

Warning: preg_replace() [function.preg-replace]: Unknown modifier ” in …

The code:

$page_name = $row['page_name']; // Example:  help
preg_replace('/RewriteRule ' . preg_quote('^' . $page_name . '/?$ page.php?mode=') . '.*/i', '', $htaccess);

This is an example of what it should fully remove:

RewriteRule ^help/?$ page.php?mode=help

Advertisement

Answer

You have to escape the expression delimiter by passing it to preg_quote as the second argument.

preg_replace('/RewriteRule ' . preg_quote('^' . $page_name . '/?$ page.php?mode=', '/') . '.*/i', '', $htaccess);

Or else your / won’t be escaped. As stated in the documentation “the special regular expression characters are: . + * ? [ ^ ] $ ( ) { } = ! < > | : -“

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement