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
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
Very short and simple example:
<?php
$text = "Hello World";
$i=0;
while ($i<strlen($text)) {
echo substr($text,$i,1);
$i+=2;
}
?>
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