Reputation:
I want to know is there any way to add mid-string delimiters in text like this:
123456789
into 123-456-789
Basically, add "-" between every 3 characters?
Also if the text is
ABCDEFGHI
A1B2C3D4E
Upvotes: 6
Views: 429
Reputation: 51561
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).
Upvotes: 2
Reputation: 96199
<?php
$i = '123456789';
echo 'result: ', wordwrap($i, 3, '-', true);
printsresult: 123-456-789
Upvotes: 5
Reputation: 994897
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.
Upvotes: 2
Reputation: 65476
For any language:
Upvotes: 1
Reputation: 882776
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
Upvotes: 3
Reputation: 340496
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.
Upvotes: 0
Reputation: 74292
In Perl:
#!/usr/bin/perl
use strict;
use warnings;
my $string = "123456789";
$string =~ /(\d{3})(\d{3})(\d+)/;
print "$1-$2-$3"
Upvotes: 0