0

I have a situation where I need to search a css file within PHP and replace all instances of the string 'logo.png' with whatever the client uploads. Let's say they upload 'logo.jpg' (notice the different file extension).

My problem is that the css content also contains a reference to an 'applogo.png' that I want to remain unchanged. But of course whenever I run the code below, it will change the 'applogo.png' to 'applogo.jpg':

$cssContent = str_replace('logo.png','logo.jpg',$cssContent);

How can I make sure that when I search and replace 'logo.png', that it ignores 'applogo.png'?

*There are instances where the quotes may or may not be included within the string, so including the quote is not reliable.

Any help or guidance towards resources is appreciated.

jmchauv
  • 147
  • 17
  • 2
    Either include the quotes in the search (and replace) string or use regexes. – Federico klez Culloca Jun 26 '18 at 12:17
  • Thank you. I just updated my original question. I forgot to add that there are instances where the quotes may not be there. – jmchauv Jun 26 '18 at 12:20
  • Can't you edit the CSS file to always include quotes ? Just wondering.. – AymDev Jun 26 '18 at 12:21
  • Is there any preceding characters like a `(` that can be used as a boundary? – revo Jun 26 '18 at 12:22
  • There are instances where the reference could look like this `(logo.png)` or this `('logo.png')`, same goes for `(applogo.png)` or this `('applogo.png')`. I could have two `str_replace` that would take care of both, but is there a cleaner way? I'm not that experienced in regex – jmchauv Jun 26 '18 at 12:23
  • I'm bad at regex too, but I know how to read the [documentation](http://php.net/manual/en/function.str-replace.php) : `str_replace(["(logo.png)", "('logo.png')"], '(logo.jpg)', $cssContent)` – AymDev Jun 26 '18 at 12:29
  • I changed the marked question. You'll need to use lookbehinds or a simple capturing group: `(?<=\('|\()logo\.png` See live demo here https://regex101.com/r/OZCj96/1 – revo Jun 26 '18 at 12:32
  • `preg_replace('/^logo\.png/', '', $cssContent);` – frosty Jun 26 '18 at 12:45

0 Answers0