Php get number from string

I have this line

@ [123: peterwateber] hi there 095032sdfsdf! @ [589: ZZZZ]

I want to get 123 and 589 , how do you use regex or something in PHP?

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

+6
source share
3 answers

Remember to see that you do not 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" } 
+6
source

The following regular expression will extract one or more numeric characters in a string:

 preg_match_all('#\d+#', $subject, $results); print_r($results); 
+2
source

There is a function called preg_match_all

The first parameter takes a regular expression. The following example matches at least one digit, followed by any number of digits. This will match the numbers.

The second parameter is the string itself, the topic from which you want to extract

The third is an array in which all matched elements will sit. Thus, the first element will be 123, the second - 589, etc.

  preg_match_all("/[0-9]+/", $string, $matches); 
+1
source

Source: https://habr.com/ru/post/915005/


All Articles