1

I have a string in following patterns.

A-B-C-D
A-AB-C-DP
AQ-B-MN-QD

and so on. The pattern follows same rule that each string has 4 group of letter(s) separated by a dash. But string might have a group with any combination of one or two letters as above.

Now what i want to do is replace the letter(s) that comes after 2nd and 3rd dash.

if the letters in group have been consistent, it would have easier for me to use strpos and substr functions to do that. But here the letters are not consistent in a group. How to do this in this scenario?

Thanks

WatsMyName
  • 4,240
  • 5
  • 42
  • 73
  • 2
    Variable-length strings with recurring patterns are simpler to work on with regular expressions. * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Oct 11 '12 at 17:56
  • Do you need to validate, as well as replace? Or are you confident (confident === you already checked) that the string is valid? – Madara's Ghost Oct 11 '12 at 17:57
  • @MadaraUchiha, I dont need to validate, I just need to replace – WatsMyName Oct 11 '12 at 17:59
  • 2
    @LoVeSmItH: JvdBerg's answer is the one for you. – Madara's Ghost Oct 11 '12 at 18:00

3 Answers3

4

I would explode the string into a array, process it and implode back to a string:

$a = explode('-', $string);
// do stuf on element 2 and 3
$string = implode('-', $a);
JvdBerg
  • 21,777
  • 8
  • 38
  • 55
2

$string = a-b-c-d;

list($a,$b,$c,$d) = explode("-",$string);

You can then concatenate from there.

1

Regex's way. Try replace $2, $3 with your value

# replace $2, $3 with the value that you want
echo preg_replace('#([^-]+)\-([^-]+)\-([^-]+)\-([A-Z]+)#', '$1-$2-$3-$4', 'AQ-B-MN-QD');
Rezigned
  • 4,901
  • 1
  • 20
  • 18