jordojuice Posted April 28, 2011 Share Posted April 28, 2011 I'm developing the last but most important piece of a project. I am using preg_replace() to replace words with word boundaries on either side. However, I am seeing that preg_replace and str_replace are not replacing multiple word strings. Is this just how things are, or can it be worked out with preg_replace? The needle is an array containing single and multiple word strings 'banana', 'banana pancakes', 'fruit cakes', 'hamburger patties'. And replace is another array containing matching replacements 'fruit', 'breakfast', 'dessert', 'awesomeness'. My only requirement is that the words that are replaced have word boundaries, which seems to work well with single words. Quote Link to comment Share on other sites More sharing options...
trq Posted April 28, 2011 Share Posted April 28, 2011 preg_replace_all. Quote Link to comment Share on other sites More sharing options...
salathe Posted April 28, 2011 Share Posted April 28, 2011 What are you using at the moment? This should provide us with a stepping stone to help you along, rather than taking wild stabs at what you're trying to do. Quote Link to comment Share on other sites More sharing options...
jordojuice Posted April 28, 2011 Author Share Posted April 28, 2011 Sure, All I have now is: $results = preg_replace('/\b' . $needle . '\b/i', $replace, $haystack); I noticed further that this only works if the needle matches the full haystack. This is obviously unacceptable. So, while 'hamburger' will be replaced, 'i want a hamburger' is not being replaced. Literally, what this project is for is military acronyms (and there are a ton of them). So, a needle array would look like: array('inf bn', 'inf div', 'ADA') and a replace array would look like: array('infantry battalion', 'infantry division', 'air defense artillery') Even if I opted to use single terms, I am still having a problem getting those replaced. When I use the haystack '1st inf bn' nothing is replaced, even while searching for single terms 'inf' and 'bn'. This is my first attempt at regular expressions, so I'm not surprised if I'm way off base. They confuse me. Quote Link to comment Share on other sites More sharing options...
jordojuice Posted April 28, 2011 Author Share Posted April 28, 2011 What I mostly need is to replace 'inf bn' in a string like '1st inf bn 1st brigade', which is just not happening. Thanks for the help. 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.