Reputation: 25
I want to pass to a new line after detecting the number in the string. So I want output to be:
nameone
2 nametwo
3 namethree
here is the code that I am running in php:
$str="nameone 2 nametwo 3 namethree";
for ($i=0;$i<=strlen($str)-1;$i++){
$char=$str[$i];
if (is_int($char)){
echo "\n".$char;
}
else if (!is_int($char)){
echo $char;
}
}
however the output is nameone 2 name two 3 namethree
. What am I doing wrong?
Upvotes: 1
Views: 57
Reputation: 17805
is_int
checks with the datatype too and not just the numbers inside it in string form.
For your case, use is_numeric
like below:
Snippet:
<?php
$str = "nameone 2 nametwo 3 namethree";
for ($i = 0; $i <= strlen($str) - 1; $i++){
$char = $str[$i];
if (is_numeric($char)){
echo "\n".$char;
}else{
echo $char;
}
}
Alternative Way:
You can use preg_replace
to achieve the same result. Just match all digits using \d
and use a line break appended with the backtracked group of the regex like below:
<?php
$str = preg_replace('/(\d)/', PHP_EOL . '\0' , $str);
echo $str;
Upvotes: 1
Reputation: 127
You can use the built-in function PHP_EOL to add a line break after detecting a number in a string.
Upvotes: 0