1
$string = "1, 2, 3, 4, 5, 6, 7, 8";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int; // output will be 12345678

I need the output will be like this :

1

2

3

4

5

6

7

8

Help me pls.

chris85
  • 23,846
  • 7
  • 34
  • 51
  • 1
    Possible duplicate of [How can I split a comma delimited string into an array in PHP?](http://stackoverflow.com/questions/1125730/how-can-i-split-a-comma-delimited-string-into-an-array-in-php) – L. Herrera Dec 15 '16 at 04:32

6 Answers6

1

I think you are over thinking it but if a regex is really needed capture all the integers then implode them.

$string = "1, 2, 3, 4, 5, 6, 7, 8";
preg_match_all('/[0-9]+/', $string, $match);
echo implode("\n\n", $match[0]);

Exploding then imploding seems like an easier approach though:

$string = "1, 2, 3, 4, 5, 6, 7, 8";
echo implode("\n\n", explode(', ', $string));

Demo: https://eval.in/697764

chris85
  • 23,846
  • 7
  • 34
  • 51
0

if you just want to show as your output you can use

$string = "1, 2, 3, 4, 5, 6, 7, 8";
$int = preg_replace('/[^0-9]+/', '<br /><br />', $string);
echo $int;

another approach (which i would use)

$string = "1, 2, 3, 4, 5, 6, 7, 8";
$int = explode(',', $string);
var_dump($int);

here all the integer value will be separated and can be use as you like

reza
  • 1,507
  • 2
  • 12
  • 17
0

Try this..Hope it will works..

The explode() function breaks a string into an array.

$string = "1, 2, 3, 4, 5, 6, 7, 8";
$arr=explode(',',$string);
foreach ($arr as $a) {
    echo $a."<br/>";
}
Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19
0
  <?php
      $string = "1, 2, 3, 4, 5, 6, 7, 8";

      $int = explode(", ",$string);

      foreach ($int as $value) {
         echo "$value <br>";
        }
 ?>

Output

1
2
3
4
5
6
7
8
chris85
  • 23,846
  • 7
  • 34
  • 51
Nmarediya
  • 1
  • 1
  • 7
0

Please try this example:

$string = "1, 2, 3, 4, 5, 6, 7, 8";     
$data= explode(',' ,$string);
echo "<pre>".implode("\n",$data)."</pre>";
Ankur Radadiya
  • 245
  • 3
  • 11
0

If you want PHP output only, then replace the second line of your code with the line below:

$int = preg_replace('/[^0-9]+/', "\n", $string);

Note the double quote for the second parameter.

But, if you want output in HTML only, use this:

$int = preg_replace('/[^0-9]+/', '<br />', $string);

Good luck.

Pieter P.
  • 109
  • 6