Finding words containing numbers and letters

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
feartheyankees
Forum Newbie
Posts: 1
Joined: Mon Aug 20, 2012 10:38 am

Finding words containing numbers and letters

Post by feartheyankees »

Hello guys,

Making an aviation website, and wanting to breakdown a string, such as this:

"COPES J75 GVE J37 SJI LEV A649 COKER UA649 PAZ UJ55 DATUL DATUL2A"

I made a regex expression, /\w+\b +[A-Z][0-9]+ \w+\b/, but it only picks up COPES J75 GVE and LEV A649 COKER. My goal for this is for it to pick up COPES J75 GVE, GVE J37 SJI, LEV A649 COKER, UA649 PAZ, and UJ55 DATUL.

However, the expression I made will not pick up two lettered words with numbers, just single lettered words. It also doesn't pick up duplicates, like "GVE" in more than one usage.

If anything else needs to be explained, I'll be happy to do so into more detail.

Thanks!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Finding words containing numbers and letters

Post by requinix »

Normally a regular expression won't backtrack into something that's already been matched by a previous iteration. To avoid that you'll need a lookahead that captures.

Code: Select all

/(\w+\b +[A-Z][0-9]+ )(?=(\w+\b))/
(which forces you to combine $1 and $2 to get the full string).

The only problem now is that your expression requires [0-9]+ in the second word but you apparently don't want that: "PAZ" and "DATUL".
Post Reply