Jump to content

[SOLVED] Replacing only certain letters in a string


Chappers

Recommended Posts

Hi,

 

Could anyone help me with this please?

 

I will be grabbing a string from a table which will be in the format *f*i where * denotes a single numeral number, so I might grab 6f7i or 4f2i and so on.

 

What I'm trying to do is use a replace function to change the f to an inverted comma ('), and the i to a speech mark ("), so 6f7i would become 6'7". It would only need to do it to the one string, not a few of them at a time. I've tried str_replace and preg_replace but can't even understand the latter yet, also can't fathom how to keep the numerals unaltered and passed over with only the letters being changed.

 

Any help greatly appreciated, especially if it means I don't have to fall back to a long list of:

if ($h1 == 4f1i) {$h1 = "4'1\"";}
elseif ($h1 == 4f2i) {$h1 = "4'2\"";} 

and so on, through all the ones I'll be using.

 

Thanks,

James

Link to comment
Share on other sites

Thanks a lot for that, it worked perfectly. I didn't know str_replace could be used like that (with the array) and now feel pretty stupid for missing the obvious that I could have just used the function to replace the letter part while leaving the numeral alone, instead thinking it had to replace the entire variable I'd pulled from my table. I was getting so bogged down in assuming it'd be a complex method for achieving what I wanted that I missed the obvious.

 

One thing, I didn't know how to put the inverted comma and speech marks into the replace part of the function without it causing problems, but it seems you can change from using inverted commas to using speech marks within the same function, as you've demonstrated.

 

Thanks again  :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.