We help IT Professionals succeed at work.
Get Started

PHP regular expression - concatenating 2 words in a sentence

gublooo
gublooo asked
on
390 Views
Last Modified: 2012-05-08
Dear Experts,

I'm sure this is a pretty easy code for you but not being good with regular expressions - I've spent hours and not yet close to doing this.

Basically what I want is - to locate a word in a sentence and concatenate it using underscore with the word before that.
Egs - word to locate - "town"

Sentence - Where are pizza shops in George town.
output - Where are pizza shops in George_town.
Explanation - remove the white space character and replace it with underscore

Sentence - I heard in M. town the weather is great now.
output - I heard in M_town the weather is great now
Explanation - here we remove the DOT and space and joined them using underscore.

The idea is, once we find the word town, find the word before that and no matter what non alphanumeric  character ( like apostrophe, single quote, double quote, space, double space, comma fullstop, hyphen) is in between - replace that character and join them using underscore.

If there are no words before town - make no changes.
Appreciate your help.
Thanks
Comment
Watch Question
Computer Co-ordinator Team Leader
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE