Home > OS >  extract number in string "IDnumber bla bla:" with php
extract number in string "IDnumber bla bla:" with php

Time:03-29

how can i extract number in string with php, eg:

string = "bla1 bla2 ID1234 bla3 bla4:"

desireable output = 1234

I used explode("ID",$string) but wrong output (=ID1234 bla3 bla4:)

Please help Thank you

CodePudding user response:

If you search a single ID and if the number is at most 10 chars you can do it with strpos and substr :

<?php
$string = "bla1 bla2 ID1234 bla3 bla4:";
$pos = strpos($string, 'ID');
if ($pos !== false)
    $n = (int) substr($string, 2   $pos, 10); // found the ID
else
    $n = null ; // not found the ID
var_dump($n); // int(1234) 
  • Related