Chappers Posted November 27, 2007 Share Posted November 27, 2007 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 Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted November 27, 2007 Share Posted November 27, 2007 When you tried str_replace, how did you try it? This should work: <?php $str = '4f11i'; $new_str = str_replace(array('f','i'),array("'",'"'),$str); echo $new_str; ?> Ken Quote Link to comment Share on other sites More sharing options...
Chappers Posted November 27, 2007 Author Share Posted November 27, 2007 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 Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted November 27, 2007 Share Posted November 27, 2007 BTW, most people in the US use the term "single quote" for what you call "inverted comma" and "double quotes" for "speech marks". Ken Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.