Manixat Posted December 20, 2012 Share Posted December 20, 2012 (edited) Heya, is there a way to find different strings in a text and replace them depending on the found string using a single replace methog ? I believe my explanation is worse than bad so I guess I have to give an example: if I have this sentence "Scott is Bob's best friend and Tod's worst enemy" if I want to replace scott with greg, bob with jeremy and tod with simon I can do this text.replace(/scott/,'Greg').replace(/bob/,'Jeremy').replace(/tod/,'Simon'); but my question is if I can do something like this text.replace(/scott|bob|tod/,/greg|jeremy|simon/) Is it possible? EDIT: I know in this case I don't have to use regular expressions, but this is just an example, in my real code I have to use regex Edited December 20, 2012 by Manixat Quote Link to comment Share on other sites More sharing options...
codefossa Posted December 20, 2012 Share Posted December 20, 2012 You could create a function that will do it from an array for strings found/replaced. Then like using preg_replace with an array in PHP, you would put the regex for each of the first array, and then the replacement in the second. Quote Link to comment Share on other sites More sharing options...
Manixat Posted December 20, 2012 Author Share Posted December 20, 2012 You could create a function that will do it from an array for strings found/replaced. Then like using preg_replace with an array in PHP, you would put the regex for each of the first array, and then the replacement in the second. Yes, I know I can do that, but my page is running in background so my goal is to use as less CPU as I can that's why I wanna avoid doing loops and using 10+ replace methods Quote Link to comment Share on other sites More sharing options...
Psycho Posted December 20, 2012 Share Posted December 20, 2012 Yes, I know I can do that, but my page is running in background so my goal is to use as less CPU as I can that's why I wanna avoid doing loops and using 10+ replace methods Even if there was a built in function that allowed you to pass arrays, such as preg_replace allows in HP, how do you think that function would actually perform the logic? it would use loops. Quote Link to comment Share on other sites More sharing options...
Manixat Posted December 20, 2012 Author Share Posted December 20, 2012 (edited) Ofcourse it would but it would also be written by somebody who actually knows what he's doing anyway I guess I found my answer, thank you guys! Edited December 20, 2012 by Manixat 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.