Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have string in format as below:

ABC 318 XY2388

I tried to use preg replace function in PHP with Regex but having no knowledge of reg ex I am not getting anywhere.

I want above string to end up like ABC 318/XY 2388

So the rule is:

  • Keep the first ABC (first batch of letters) untouched.
  • Put a space between letter(s) and number occurring after ABC.
  • replace space between second batch of numbers and letters with forward slash

I will appreciate any help on this.

share|improve this question

closed as off-topic by John Conde, andrewsi, JDB, HamZa, Graviton Jul 19 '13 at 3:46

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist" – andrewsi, JDB, HamZa, Graviton
If this question can be reworded to fit the rules in the help center, please edit the question.

    
What about the XY? Are they removed? –  Racso Jul 9 '13 at 14:50
    
sorry modified the question. Really sorry about this. –  Sahil Jul 9 '13 at 14:53
    
What kind of letters/digits? Unicode? Only ASCII? Also, there already is a space between ABC and 318, but not between XY and 2388 - that doesn't match your description. –  Tim Pietzcker Jul 9 '13 at 14:57

1 Answer 1

up vote 0 down vote accepted

This code changes the string using the corrected rule/example you are giving:

  $input = "ABC 318 XY2388";
  $output = preg_replace("/([A-Z]*) (\d*) ([A-Z]*)(\d*)/","$1 $2/$3 $4", $input);
  echo $output;

Result: ABC 318/XY 2388

share|improve this answer
    
Slightly changed the question. Sorry about this. –  Sahil Jul 9 '13 at 14:54
    
Thanks a lot!, If the first batch of letters were unknown then what happens? –  Sahil Jul 9 '13 at 15:02
    
I mean if the ABC was not know then how can I solve it?, in future it may be ABB, AVC or anything –  Sahil Jul 9 '13 at 15:03
    
Modified the answer so the first batch is dynamic (in the previous answer, it was fixed to "ABC") :) –  Racso Jul 9 '13 at 15:03
    
Thanks Much appreciated... –  Sahil Jul 9 '13 at 15:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.