cahamilton Posted April 24, 2009 Share Posted April 24, 2009 Would it be possible to replace multiple instances of one character for a single replacement instance. For example: String 1 Name1 Surname1 Name2 Surname2 Name3 Surname3 What I want it to look like is: String 1 Result Name1+Surname1+Name2+Surname2+Name3+Surname3 So far I'm using this method: $string1 = str_replace(" ","+",$string 1); And what this is returning is a string like this: String 1 Name1+Surname1++++++Name2+Surname2+++++++++++++++Name3+Surname3++++++++++++++ Would it be possible to do this, as I want to use the result as a URL query? Quote Link to comment Share on other sites More sharing options...
.josh Posted April 24, 2009 Share Posted April 24, 2009 $string1 = preg_replace('~\s+~','+',$string1); Quote Link to comment Share on other sites More sharing options...
cahamilton Posted April 24, 2009 Author Share Posted April 24, 2009 Brilliant! Thanks for your help, it worked a treat. So what exactly did the "preg_replace('~\s+~' " part of the code do? Quote Link to comment Share on other sites More sharing options...
.josh Posted April 24, 2009 Share Posted April 24, 2009 It's a regular expression, or regex, for short. Pattern matching. The pattern says look for one or more spaces or tabs in a row and replace it with a '+'. The \s stands for the space or tab. The + is the quantifier: 1 or more of the previous thing (the \s). The ~...~ are delimiters, signifying the start and end of the pattern. The 2nd argument of the preg_match function is what you want to replace what is matched in the pattern with. In your case, you want to match every instance of 1 or more space/tab chars in a row with a plus sign. Quote Link to comment Share on other sites More sharing options...
cahamilton Posted April 24, 2009 Author Share Posted April 24, 2009 Great, thanks for explaining that! Its good to know for future tense . Im gradually getting there was PHP lol 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.