Jump to content

preg_replace() only replaces single words


jordojuice

Recommended Posts

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.

Link to comment
Share on other sites

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.

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.