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.

0

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Are you in a web browser?
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/>";
}

Comments

0

Please try this example:

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

Comments

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

1 Comment

[^0-9] is more simply \D.
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

Comments

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.

1 Comment

[^0-9] is more simply \D.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.