Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php get the number from a string

I have this string

@[123:peterwateber] hello there 095032sdfsdf! @[589:zzzz]

I want to get 123 and 589 how do you that using regular expression or something in PHP?

Note: peterwateber and zzzz are just examples. any random string should be considered

like image 299
Peter Wateber Avatar asked May 06 '12 05:05

Peter Wateber


3 Answers

Don't forget the lookahead so you don't match 095032:

$foo = '@[123:peterwateber] hello there 095032sdfsdf! @[589:zzzz]';
preg_match_all("/[0-9]+(?=:)/", $foo, $matches);
var_dump($matches[0]); // array(2) { [0]=> string(3) "123" [1]=> string(3) "589" }
like image 137
AlienWebguy Avatar answered Sep 19 '22 23:09

AlienWebguy


The following regex will extract one or more numeric characters in a row:

preg_match_all('#\d+#', $subject, $results);
print_r($results);
like image 41
rjz Avatar answered Sep 22 '22 23:09

rjz


There is a function called preg_match_all

The first parameter accepts a regular expression - The following example shows 'match at least one digit, followed by any number of digits. This will match numbers.

The second param is the string itself, the subject from which you want extraction

The third is an array into which all the matched elements will sit. So first element will be 123, second will be 589 and so on

    preg_match_all("/[0-9]+/", $string, $matches);
like image 45
Nikhil Baliga Avatar answered Sep 23 '22 23:09

Nikhil Baliga