Home > Enterprise >  extract only numbers from textarea using php
extract only numbers from textarea using php

Time:01-27

i have a textarea each line in textarea contains numbers or names , i want to extract only number from textarea .

this my code


<?php 

    $allUsers = $_POST['allusers'];
    foreach(explode("\n", $allUsers) as $line) {
        
        if (is_numeric($line)) {
            echo $line."\n";
        }

    }
?>

and example of textarea data :

<textarea>
156444
978455
amoka
123
auman
</textarea>

CodePudding user response:

A solution using regex

 $text = 'ggd 56756 sadhgsagdahdgash  dhjghjg 324324 3  432 423 4 324hjhghjgjh 343434 34 34 hgjhghj';
    
    preg_match_all('/\d /', $text, $matches);
    
    $numbers = $matches[0];
    
    print_r($numbers);

CodePudding user response:

Remove whitespace around the line before checking if it's numeric.

    foreach(explode("\n", $allUsers) as $line) {
        $line = trim($line);
        if (is_numeric($line)) {
            echo $line."\n";
        }
    }
  •  Tags:  
  • php
  • Related