Insertion of point every 5 characters

6

I have the following string: "AAAAABBBBBCCCCC"

There is a script that places a "." every 5 characters?
In case this script would return: "AAAAA.BBBBB.CCCCC."

    
asked by anonymous 20.12.2014 / 04:31

4 answers

9

One solution is the function chunk_split() that serves precisely to split the string into smaller pieces:

$str = chunk_split("AAAAABBBBBCCCCCDDDDD", 5, '.');

Example on Ideone :

var_dump($str); // AAAAA.BBBBB.CCCCC.DDDDD.

Note: I am suggesting this function because in your question you asked not only to add . to each X positions, but to the result to end with . . With this function, you satisfy both requirements.

    
20.12.2014 / 23:22
4

You can do this as follows:

<?php 
    $string = "AAAAABBBBBCCCCC";
    $array = str_split($string, 5); 
    $novaString = implode(".", $array);
    echo $novaString;
?> 

Explaining What Happens: You have separated the string into several Strings, and saved them into an array called $ array. The result is:

  

$ array [0] has the values AAAAA

     

$ array [1] has the values BBBBB

     

$ array [2] has CCCCC values

And after splitting into the arrays the implode is used to concatenate the strings stored in the array with the dot (.). I hope you have helped.

    
20.12.2014 / 04:59
4

Another way to add a string based on a range (5 characters) is to use the wordwrap function. . The third parameter is the character to be entered and the fourth forces php to add the character in the exact range , because the purpose of the function is to add the word between words and how its string is something only fourth parameter is required.

$str = "AAAAABBBBBCCCCCDDDDD";
$intervalo = 5;
$str_formatada = wordwrap($str, $intervalo, '.', true);

echo $str_formatada;

Output:

AAAAA.BBBBB.CCCCC.DDDDD

phpfiddle - example

Example of the fourth parameter:

1 - Omitted

$str = 'A very long woooooooooooord';
$str_formatada = wordwrap($str, 3, "<br>");

echo $str_formatada;

Output:

A
very
long
woooooooooooord

As the words were smaller or larger than the specified range (3), the function ended by adding <br> between them. See how it works when the fourth parameter is marked true, now the string is broken to exactly 3 characters even if it cuts or spoils the word.

2- With the fourth parameter

Output:

A
ver
y
lon
g
woo
ooo
ooo
ooo
ord
    
20.12.2014 / 15:29
3

Since you have raised the hare on multibyte , I will leave an alternative with such support:

$string = 'aaaaabbbbbcccccdddddeeeee1111122222maçãsefeijões';

$new = implode(

    '.',

    preg_split(

        '/(.{5})/us',

       $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
    )
);

This produces:

string 'aaaaa.bbbbb.ccccc.ddddd.eeeee.11111.22222.maçãs.efeij.ões' (length=60)
    
20.12.2014 / 21:22