Home > Net >  How to pass to a new line after detecting a number in a string in php?
How to pass to a new line after detecting a number in a string in php?

Time:08-11

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?

CodePudding user response:

You can use the built-in function PHP_EOL to add a line break after detecting a number in a string.

CodePudding user response:

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;
    }
}

Online Demo


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;

Online Demo

  •  Tags:  
  • php
  • Related