1

I have the following string:

$str = "ABACADAF";

I am using the following code:

$first2 = substr($str, 0, 2);

I want to get the following output:

output => `AB,AC,AD,AF`

(Every two characters separated by comma)

But the result I'm getting is not correct.

I checked the php manual but that is not helping, is there some foreach loop to iterate through all the string characters?

6 Answers 6

4

Not tested, but should be something along these lines:

<?php

$string = "ABACADAF";
$split = str_split($string, 2);
$implode = implode(",", $split);

echo $implode;

?>
Sign up to request clarification or add additional context in comments.

1 Comment

you code seems net, but it is not working with me here foreach ($ro as $key=>$value) { $str = $value['ro_code']; $split = str_split($str, 2); $implode = implode(",", $split); echo $implode; } Not working
3

You are looking for str_split function. You can do like this:

$sResult = join(',', str_split($sData, 2));

Alternatively, you can do it via regex:

$sResult = preg_replace('/(..)(?!$)/', '$1,', $sData);

4 Comments

I'm not sure why people are upvoting this one because while it does show one of the keys to what the OP was kind of looking for, it doesn't explain anything. It's like a replacement for Google.
That is because - first of - an answer was the first (so Tom's answer expected to be a comment with an issue about join), and - second - this leaves a way for OP to think and try it for himself. I beleive that's more SO style.
Your answer outputs this A,B,A,C,A,D,A,F You should test your code.
Anyway, I've added another solution to make an answer better. Thanks!
1

Here's a function that you can use to output from a foreach. We're finding two capital letter matches and putting them into an array, then we implode that array() to make a string.

<?php
    function splitter($string){
        preg_match_all('/[A-Z]{2}/', $string, $matches);
        $newstring = implode(',',$matches[0]);
        return $newstring;
    }


    $strings = array("ABACADAF","ACABAFAC","AAABAFAD","ACACADAF");
    foreach($strings as $string){
        echo splitter($string)."\n";    
    }
?>

Output

AB,AC,AD,AF
AC,AB,AF,AC
AA,AB,AF,AD
AC,AC,AD,AF

If you're running a lot of them (millions of lines) you can use this function instead. It's much quicker.

function splitter($string){
    $newstring = substr(chunk_split($string, 2, ','), 0, -1);
    return $newstring;
}

2 Comments

Yet again :p Why not use that regex I've provided, next - that could be done by one regex (see my answer)
@AlmaDoMundo Even though it looks more elegant code-wise your preg_replace suggestion is actually slower than the preg_match function and the non-preg functions (of course). So it's cool, but a little more complicated in terms of processing.
1

You could do it like this or recursively as well.

<?php
for ($i=0; $i< strlen($str); $i=$i+3)
{
    $str = substr($str,i,2).",".substr($str,3);
}
echo $str;
?>

I personally prefer the recursive implementation:

<?php

    function add_comma($str)
    {
        return substr($str, 0, 2,).','.add_comma(subtr($str,3));
    }
    echo add_comma($str);

?>

2 Comments

Getting all Rube Goldberg on us eh?
That's where the recursion comes in... Although the line length is still the same... :/
0

While this is doable with a for loop, it is cleaner (and maybe faster), and more strait-forward in TomUnite's answer.

But since you asked...
With a for loop you could do it like this:

$withCommas = substr($string, 0, 2);

for($i=0; $i < strlen($string); $i += 2){
    $withCommas+= "," . substr($string, $i, $i+2);
}

Comments

0

Here is the solution and Same output of your problem: I personally tested it :

<?php
$str     =  "ABACADAF";
$first   =  substr($str, 0, 2);
$second  =  substr($str, 2, 2);
$third   =  substr($str, 4, 2);
$fourth  =  substr($str, 6, 2);

echo $output  =  $first.",".$second.",".$third.",".$fourth;     

?>

2 Comments

What happens when the user changes $str to be shorter or longer? The idea behind programming is to abstract your functions for broader usage. It is not good programming to limit any function to something so case specific as this.
I agree with you. But he defined his string statically, so i showed him the simplest way to perform this solution. And it will work for him. But on the other side your point is valid. A function will be way useful for different length of strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.