Extract a single (unsigned) integer from a string
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
How Do I Take Out Only Numbers From A PHP String?
Correct variant will be:
$string = "Hello! 123 How Are You? 456";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
How to get only the number from a string?
filter_var
You can use filter_var
and sanitize the string to only include integers.
$s = "Lesson 001: Complete";
echo filter_var($s, FILTER_SANITIZE_NUMBER_INT);
https://eval.in/309989
preg_match
You can use a regular expression to match only integers.
$s = "Lesson 001: Complete";
preg_match("/([0-9]+)/", $s, $matches);
echo $matches[1];
https://eval.in/309994
Get numbers from string with PHP
You can use regular expressions for this. The \d
escape sequence will match all digits in the subject string.
For example:
<?php
function get_numerics ($str) {
preg_match_all('/\d+/', $str, $matches);
return $matches[0];
}
$one = 'foo bar 4 baz (5 qux quux)';
$two = 'bar baz 2 bar';
$three = 'qux bar 12 quux (3 foo)';
$four = 'foo baz 3 bar (13 quux foo)';
print_r(get_numerics($one));
print_r(get_numerics($two));
print_r(get_numerics($three));
print_r(get_numerics($four));
https://3v4l.org/DiDBL
Extract numbers from a string in PHP with Regex
Try this:
$only_digits = preg_replace('/\D+/', '', $string);
Upper \D
- the opposite of \d
- matches non-digits.
Demo (regex101)
How to extract integer and decimal numbers in PHP string correctly?
You're using a .
for thousands and a ,
for decimals, and it looks like your text is intended for humans so there will always be a number immediately before a .
and ,
.
So what you want is 1 or more numbers, followed by 0 or more thousand-groups (a .
followed by 3 more numbers), optionally followed by exactly one ,
and one or more numbers.
One or more numbers: [0-9]+
0 or more thousand-groups: (\.[0-9]{3})*
Optionally a `,` and one or more numbers: (,[0-9]+)?
Combined: [0-9]+(\.[0-9]{3})*(,[0-9]+)?
$string = 'María vive en un pueblo de 25 957 habitantes y cobra 1859 euros al mes. OJO: no sé si os habéis fijado, pero los números del último ejemplo
no llevan un punto o una coma separando los millares (25.957 o 1.859). Sé que resulta extraño, pero la nueva normativa de la R.A.E.
dice que los números de cuatro cifras NO llevarán separación (1859) y los números de cinco cifras o más NO llevarán ni puntos ni comas,
sino una separación (25 957 o 1 343 392). El 94% de los niños ha traído los deberes hechos. He pagado $50,95 dólares.';
$matches = [];
preg_match_all('/[0-9]+(\.[0-9]{3})*(,[0-9]+)?/', $string, $matches);
print_r($matches[0]);
/*
Array
(
[0] => 25
[1] => 957
[2] => 1859
[3] => 25.957
[4] => 1.859
[5] => 1859
[6] => 25
[7] => 957
[8] => 1
[9] => 343
[10] => 392
[11] => 94
[12] => 50,95
)
*/
Extract numbers (not digits) from a string in PHP
(?:^|(?<=[,.\s]))\d+(?=[,.\s]|$)
You can use lookaheads
for this.See demo.
https://regex101.com/r/vD0sJ3/3
$re = "/(?:^|(?<=\\s))\\d+(?=\\s|$)/si";
$str = "34681A Lincoln Street Surf City NJ 08008";
preg_match_all($re, $str, $matches);
or thru replace
(?:^|(?<=[,.\s]))\d+(?=[,.\s]|$)\K|.
See here
$re = "/(?:^|(?<=[,.\\s]))\\d+(?=[,.\\s]|$)\\K|./i";
$str = "James 3, Aptt.27, 34681/A Lincoln St Surf City NJ 08008";
$subst = "";
$result = preg_replace($re, $subst, $str);
Get numbers that immediately follow @ symbol in string
(Using a preg_match_all
function as an example, but the function doesn't matter, the Regex within does:)
$inputString = "@3115
Hello this is a test post.
@115
Test quote";
preg_match_all("/@(\d+)/",$inputString,$output);
//$output[1] = "3115";
//$output[2] = "115";
This will find a @
character, and then find \d
which is any numerical value, and then +
means to catch [the numerical value] one or more times. the ()
makes this a capture group so will only return the number found and not the @
preceeding it.
Extract number from html string
You can use strip_tags
<?php
$a = '<td>15</td>';
echo strip_tags($a);
Find the position of the first occuring of any number bigger than certain number in a string
function firstNumPos($text, $number){
preg_match_all('!\d+!', $text, $match);
foreach ($match[0] as $value) {
if ($value > $number) {
return strpos($text, $value);
}
}
}
echo firstNumPos('20 plus 1000 is not 20000.', 10000);
Related Topics
Http Options Request on Azure Websites Fails Due to Cors
Best Way to Allow Plugins for a PHP Application
Setup Http Expires Headers Using PHP and Apache
How to Identify Server Ip Address in PHP
String Contains Any Items in an Array (Case Insensitive)
Track When User Hits Back Button on the Browser
Header Location Not Working in My PHP Code
How to Find the Socket Transport "Ssl" - Did You Forget to Enable It When You Configured PHP
How to Connect to MySQL Database in PHP Using MySQLi Extension
How to Use PHP to Dynamically Publish an Ical File to Be Read by Google Calendar
How to Integrate Wordpress Template with Codeigniter
Verify Imagemagick Installation
How to Check If a Request If Coming from the Same Server or Different Server