php get the number from a string
Asked Answered
P

3

7

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

Pointenoire answered 6/5, 2012 at 5:23 Comment(0)
R
7

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" }
Route answered 6/5, 2012 at 5:35 Comment(0)
A
2

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

preg_match_all('#\d+#', $subject, $results);
print_r($results);
Autocade answered 6/5, 2012 at 5:27 Comment(0)
K
1

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);
Keek answered 6/5, 2012 at 5:27 Comment(4)
hey.. I forgot to mention In my post my priority in getting the number in the string is matched when "@[123:some text here]" is foundPointenoire
I am sorry I didn't get that. Could you be a little more clear? Do you want the numbers to be printed?Keek
"@[123:peterwateber]" preg_match_all should be based. if the string is "hello nikhil @[123:peterwateber] its 6th of may" the output should be "123" when preg_match_all. Therefore, 123 should be get in the string that has the following value "@[number:string]"Pointenoire
Oh, then use this - preg_match_all("/@[[0-9]+:[A-Za-z]+]/", $string, $matches); It says - get an '@', followed by open square brackets, one or more digits followed by a colon, followed by one or more characters (upper and lower case) followed by close of square bracket Then do the previous preg match on result of this.Keek

© 2022 - 2024 — McMap. All rights reserved.