-5

Is there simple function? How to split string and show every 2 symbol of a string in php?

    $text = "Hello World";

// output needed: H l o W r d
aronsimt
  • 25
  • 10

2 Answers2

0

Very short and simple example:

<?php

 $text = "Hello World";

 $i=0;
 while ($i<strlen($text)) {
    echo substr($text,$i,1);
    $i+=2;
 }

?>
MatWer
  • 136
  • 6
  • 1
    Rather than counting the length of the string on every iteration, you could calculate ahead of the loop. You can use the shorter offset syntax to get your character from the string: `for($i=0, $l=strlen($text); $i<$l; $i+=2) echo $text[$i];` – Progrock Oct 19 '19 at 21:20
  • thats true ... I just want to reflect an easy to understand method for a Newcommer :-) – MatWer Oct 19 '19 at 21:28
  • Thank you for your help! its working, but i add `mb_substr($text,$i,1);` for unicode – aronsimt Oct 20 '19 at 02:03
  • nice if it works for you ... mb_substr() you might be right, but I want to give you an easy example to understand with not so much extras you have to think about :-) – MatWer Oct 20 '19 at 20:06
0

Here are a few examples that include spacing out with another character. Notice the trailing characters on some solutions.

The last two are there for fun more than anything, though 'preg_split'ting might be useful if you need to handle unicode, as in the last example.

<?php
$text = "Hello World";
$spacer = '.';
$divider = "\n\n%d:\n";

printf($divider, 1);

for($i=0, $l=strlen($text); $i<$l; $i+=2)
    echo $text[$i], $spacer;

printf($divider, 2);

for($i=0, $l=strlen($text); $i<$l; $i++)
    echo $i%2==0 ? $text[$i] : $spacer;

printf($divider, 3);

for($i=0, $l=strlen($text); $i<$l; $i++)
    echo $i&1 ? $spacer : $text[$i];

printf($divider, 4);

foreach(str_split($text, 2) as $couplet)
    echo $couplet[0], $spacer;

printf($divider, 5);

echo implode(
    $spacer, 
    array_map(
        'reset', 
        array_chunk(
            str_split($text), 
            2
        )
    )
);

printf($divider, 6);

echo implode(
    $spacer,
    array_column(
        array_chunk(
            preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY), 
            2
        ),
        0
    )
);

Output:

1:
H.l.o.W.r.d.

2:
H.l.o.W.r.d

3:
H.l.o.W.r.d

4:
H.l.o.W.r.d.

5:
H.l.o.W.r.d

6:
H.l.o.W.r.d
Progrock
  • 7,373
  • 1
  • 19
  • 25