2

I am trying to replace a series of plane codes that are strings in PHP.

For example, 757-252 string should become a 752 string

It takes the first two digits before the hypen, and the first digit after the hyphen.

There are three conditions that make this complicated where I can't just use explode and I think need to use RegEx:

  1. The digit before the hyphen may be more than just a single digit, and it MAY be alpha numeric.
  2. The last three digits in the example above is a variable length and can be alpha or numeric.
  3. There are values that DON'T fit this pattern that I need to be left alone (i.e. DHC-8-103)

Any thoughts

RegEx - Working at RegExPal.com

7[0-9][0-9a-zA-Z]+\-[0-9a-z-A-Z][0-9a-zA-Z]+

PHP Attempt to Replace Not Working

$aircraft = '757-252';

$pattern = '/(7)(0-9)(0-9a-zA-Z)+-(0-9a-zA-Z)(0-9a-zA-Z)+/';
$replacement = '\\1\\2\\4';

$aircraft_code = preg_replace($pattern , $replacement , $aircraft);
2
  • 2
    For starters, you've lost the [ ] brackets from your groups, so they aren't functioning as ranges in character classes like you expect. Instead, you get the literal string "0-9", for example. Commented Jan 2, 2014 at 1:05
  • I originally had them as ` [ ] ` and that didn't work either. I saw in other PHP specific examples where there weren't the ` [ ] ` but rather the ` ( ) ` so I thought I'd try that. Commented Jan 2, 2014 at 1:20

3 Answers 3

1

You should check for the beginning of $aircraft value with ^ then capture first 2 digits and the one after hyphen:

^(7\d).+?(\d).*$

And your code:

$aircraft = '757-252';
$pattern = '/^(7\d).+?(\d).*$/';
$replacement = '$1$2';
$aircraft_code = preg_replace($pattern , $replacement , $aircraft);
// echo $aircraft_code; // output: 752
Sign up to request clarification or add additional context in comments.

Comments

1

Your pattern has changed from the working Regex (missing capture groups), I think your pattern needs to be this:

$pattern = '/(7)([0-9])([0-9a-zA-Z]+)-([0-9a-z-A-Z])([0-9a-zA-Z]+)/';

I'm also a bit rusty at PHP, but I don't think you need to escape the backslashes in your replacement string if you're using '.

Comments

0

I'd use:

$pattern = '/.*\b(7\d)[^-]*-(\w).*/';
$replacement = '$1$2';

8 Comments

@revo: It'll give 75w as expected.
w is not expected as an alphabetical character
@revo: This must be clarified by OP. For me, it's OK.
It's clarified already first two digits before the hypen, and the first digit after the hyphen.
@revo: Right, but the second condition says: The last three digits in the example above is a variable length and can be alpha or numeric.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.