Thursday, 15 May 2014

regex - PHP replace part of the URL in css file -


I need to convert related URLs into my server static urls in my CSS files.

For example, I have a CSS rule:

[/ public / images ...] or ['/ public / images ...'], or [. ./public/images ...] or ['..//public/images ...'] and I need to convert all of these URLs into my static server's CDN:

  / Public / images ... - & gt; //static.mysite.com/public/images ... '/ public / images ...' - & gt; '//static.mysite.com/public/images ...' ../ Public / Images ... - & gt; //static.mysite.com/public/images ...  

I wrote a regular expression to do this, but this does not work with '../' URL here Is:

  $ fileRawContent = file_get_contents ($ filePath); $ ReplaceContent = preg_replace ('/' ('\'? (? '\'. \\.). \ / Public \ / images. *) \ '? \) /', "($ Static server $ 1) , $ FileRawContent);  

This only works for / public / images, but .. / public / not for images ...

Please advise as I said . Thanks!

This PHP preg_replace describes you:

 Notice starts at  preg_replace ("/(')?(\.).(?/public\/images.*'?)/", "$ 1 $ static server $ 3" ​​// $ 1 , $ 3 at the end, $ fileRawContent);  

Test run:

$ staticServer = '//static.mysite.com'; $ FileRawContent = "'../public / images ...'"; $ Replacement content = preg_rele ("/ (')? (Ssi)? (ATC / public / image. *'?) /", "$ 1 $ static server $ 3", $ $ $ file content); Print $ replacement content;

Output:

  '// static.mysite.com/public/images ...'  

Similarly:

/ public / images ... - & gt; //static.mysite.com/public/images ... '/ public / images ...' - & gt; '//static.mysite.com/public/images ...' ../ Public / Images ... - & gt; //static.mysite.com/public/images ...

Regular Expression Explanation:

  ( ')? (\. \.)? (\ / Public \ /images.* '?)  

We start with the same quote in parentheses. It gives us 1) question mark ? and 2) It can capture it for interpolation in our replacement parameters, then we will have two duration . Wrap in brackets and make them optional ? . (They have been captured in the variable $ 2 , but we do not use it.) Finally we capture the public image path after zero or more characters. Are there. . * and an optional ? Single quote.


No comments:

Post a Comment