Preg_replace can't get initial string piece

I need to change the end of a filename returned by woo_logo
it return something like http://content/images/mylogo.png
I want to change it to http://content/images/mylogo-fr.png
I don’t know the file name so I need to use the .png
I think for a start the . is a problem. Can anyone show me how to do this?

preg_replace("/\./png/", "-fr.png", $woo_options['woo_logo']);

You don’t need preg_replace for this, str_replace will work just fine:

str_replace('.png', '-fr.png', $woo_options['woo_logo']);

EDIT: however, seeing that the value is coming from $woo_options, maybe you should just change the option instead of throwing code at it?

3 Likes

I would also be tempted to first test if the lowercase filename had a .png extension. If true then apply str_replace to the period and retain the case insensitive file extension.

Hopefully there is only a single period :frowning:

Thread seems to be making assumptions that need to be verified:

Do all files returned always end in .png? You’ve got no JPG’s? No GIF’s? What about JPEGs?
Do you always want to make it a .png if it isnt a png?
What if the file name ends in -fr.png already?

1 Like

Yes, unless it is known that “.png” is the only match pattern and will forever always be the only match pattern a breaking change may come back to bite if not planned for.

I think that would be the most efficient long term and probably easier if you don’t need to know match patterns. I know personally that once patterns start getting messed with it’s all too easy to break things horribly. obligatory: SAVE BACKUPS

1 Like

well it is my site, png is always used for this logo file as it uses transparency. I have total control of that.
the filename should always therefor end in .png
The situation is this, the $woo_options comes from a WP plugin. I do not want to change that plugin. It is setup to display a image file which is uploaded via its interface. My issue is that my site is bi-lingual, I can have 2 image files with the same name, only difference being one has -fr in the filename.
In the code for Wordpress header template I detect if the language is french then swap the image by changing the filename.
Does that make sense?

These two statements do not meld.

I mean I may over time wish to use different file names but I have control of the extension

So… instead of doing a preg_replace or a str_replace…

if(mysiteisfrench) { $logofile = 'mylogo-fr.png' } else { $logofile = 'mylogo.png'; }

true I could just hardcode it and always use the same filename. But then I am bypassing the built in code which pulls the logo file name AND path from the themes WP interface. The path changes as upload folders are organized by date. I still prefer to just add the -fr to the filename in $woologo
But I do see your point. If it seems a hassle I will hardcode.

I got this to work using the string replace suggestion. Thanks