views:

191

answers:

9
+5  Q: 

Splitting text

I want to know is there any way to split text like this:

123456789 into 123-456-789

as to add "-" after every 3 characters?

Just wanted to know, as I know the reverse, but how to do this is over my head. ;)

and also if the text is

ABCDEFGHI OR A1B2C3D4E or any other format 
without any space between the characters !

languge : PHP only
A: 

In Perl:

#!/usr/bin/perl

use strict;
use warnings;

my $string = "123456789";
$string =~ /(\d{3})(\d{3})(\d+)/;

print "$1-$2-$3"
Alan Haggai Alavi
A: 

You can do it with (among other means) a regular expression match and replace. The exact syntax depends on the tool or programming language you are using. For instance, one way to do it in Perl would be

$a = "123456789";
$a =~ s/(\d{3})/$1-/g;
chop($a);
print $a;

Line 2 replaces every 3 digits for the same 3 digits and a dash. With chop() we delete the trailing dash.

There is another question here. What to do when the string doesn't contain a multiple by 3 amount of digits? If such strings were allowed, then the above snippet would need modification.

Also, depending on the specifics of the case, you might get away with simple substring replacement, or string slicing.

Vinko Vrsalovic
This seems to chop off a digit if the number of digits is not a multiple of 3.
Svante
Did you read paragraph 4? :)
Vinko Vrsalovic
what if its ABCDEFGHI OR A1B2C3D4E then how to split the text and in php only
Heh, no, I seem to have stopped at the chop.
Svante
+1  A: 

In the interest of completeness, here is a Python solution:

>>> a = "123456789"
>>> a[0:3] + "-" + a[3:6] + "-" + a[6:9]
'123-456-789'

Since you updated your question to specify a PHP solution, this should work:

substr($a, 0, 3) . "-" . substr($a, 3, 3) . "-" . substr($a, 6, 3)

See substr for more information on this function. This will work not only for digits, but for alphabetic characters too.

Greg Hewgill
+2  A: 

I'm not a big fan of regexes for simple string extraction (especially fixed length extractions), preferring them for slightly more complex stuff. Almost every language has a substring function so, presuming your input has already been validated, a simple (pseudo-code since you haven't specified a language):

s = substring (s,0,3) + "-" + substring (s,3,3) + "-" + substring (s,6,3)

If you want it every three characters for a variable length string (with odd size at the end):

t = ""
sep = ""
while s != "":
    if s.len <= 3:
        t = t + sep + s
        s = ""
    else:
        t = t + sep + substring (s,0,3)
        s = substring (s,3)
    sep = "-"
s = t
paxdiablo
but what about ABCDEFGHIOR A1B2C3D4E
What about it? If the spec is to handle any string, the above code will handle any string. It doesn't have to be numeric.
paxdiablo
+1  A: 

I think that this can be sanely done in a regex with lookahead:

s/(.{3})(?=.)/$1-/g

Since you mentioned PHP in a comment:

preg_replace ("/(.{3})(?=.)/", "$1-", $string);

edit: After VolkerK showed wordwrap, I found chunk-split in the documentation:

$new_string = chunk_split ($string, 3, '-');

This has the advantage that it also works when there are spaces in the string (wordwrap would prefer to break at the spaces).

Svante
Your definition of sane is at odds with mine :-)
paxdiablo
Because of the lookahead?
Svante
A: 

One more Perl example. This doesn't remove final groups smaller than three, and it leaves initial groups of less than three digits alone. It's based (pretty shamelessly) on the "money numbers" example in Learning Perl (page 212 of the 5th ed):

#!/usr/bin/env perl
use strict;
use warnings;

print "Gimme' a number: ";
chomp(my $number = <STDIN>);

1 while ($number =~ s/([0-9]{3})([0-9]+)/$1-$2/);

print "Now it's $number\n";
Telemachus
+1  A: 

Yet another Python version:

>>> x="123456789"
>>> out=[x[i:i+3] for i in xrange(0, len(x), 3)]
>>> print "-".join(out)
123-456-789
MAK
+1  A: 

For any language:

  • Create an empty string variable called "result"
  • Create an integer counter variable, "i", which increments until the length of the original string (the one with the number)
  • Append each character from the original string to "result"
  • If i modulo 3 (usually % or mod) is zero, append a dash to "result"
Chris S
+4  A: 
<?php
$i = '123456789';
echo 'result: ', wordwrap($i, 3, '-', true);
prints
result: 123-456-789

see http://php.net/wordwrap

VolkerK
ABCDEFGHI OR A1B2C3D4E or any other format then what ?
yes this works porfectly ....