Re: regular expression and forbidden words

From: Date: Wed, 18 Jul 2007 17:41:19 +0000
Subject: Re: regular expression and forbidden words
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-259134@lists.php.net to get a copy of this message
Nicolas Quirin wrote:
Hi, i'm french, i'm using regular expressions in php in order to rewrite hyperlink tags in a specific way before apache output is beeing sent to client. Purpose is to replace href attribute of any A html tag by a javascript function calling an ajax loader. Currently I have wrote that: $pattern = '/<a href="(http:\/\/dev.netdoor.fr|(\.))\/index.php\?page=(.*?)">(.*?)<\\/a>/i'; $replacement = '<a href="javascript:void(0);" OnClick="javascript:yui_fastLoader(\'./systeme/chargeur.php?page=$4\');">$5</a>'; $html_mark = preg_replace($pattern, $replacement, $html_mark); it works, but it's too permissive, it replaces too much links (some links with some get parameters must stay unchanged) I don't really understand my pattern...it's a little strange for me...lol I wouldn't like to rewrite links that contains any of the following words in get parameters (query string): noLoader noLeftCol skipallbutpage skipservice i would like to rewrite only link that begin with 'http://dev.netdoor.fr' or '.' examples: <a href="http://dev.netdoor.fr/index.php?page=./comptes/index.php&noLoader&noLeftCol&idx=6&bdx=423&skipservice">test</a> =>must be not rewritted! <a class="myclass" href="./index.php?page=./comptes/mediatheque/index.php&filter=mov;flv;mpeg&idx=7">name</a> =>must be rewritted like this : <a class="myclass" href="javascript:void(0);" OnClick="javascript:yui_fastLoader(\'./systeme/chargeur.php?page=./comptes/mediatheque/index.php&filter=mov;flv;mpeg&idx=7\');">name</a> Please help me...:0) best regards nicolas
It's complicated. I'd resort to using a callback. Even if it's possible with just patterns, it wouldn't be very readable! Something like this: if (!function_exists('make_replacement')) { function make_replacement($m) { $n=$m[2]; if (preg_match('~^(http://dev.netdoor.fr|\.)/index\.php\?(.*?)$~',
        $n,$mm)) {
if (!preg_match('~noLoader|noLeftCol|skipallbutpage|skipservice~',
         $mm[2])) {
    $n='javascript:void(0);" '.
      'OnClick="javascript:yui_fastLoader(\'./systeme/chargeur.php?'.
      $mm[2].'\')';
} } return $m[1].'href="'.$n.'"'.$m[3]; } } $pat='~(<a.*?\s)href="(.*?)"(.*?>)~i'; $html_mark=preg_replace_callback($pat,'make_replacement',$html_mark); Ben.

« previous php.general (#259134) next »