get number from string php

PHP: Get numbers from a string.

This is a short PHP tutorial on how to get numbers from a string. To do this, we will extract the numbers using the function preg_match_all.

The preg_match_all function.

The preg_match_all function allows us to match certain characters using regular expressions. In our case, we want to match numerical values.

Getting integers / whole numbers from a string.

If you’re looking to extract whole numbers from a string, then you can use the following piece of code:

If you run the code above, you will get the following result:

get number from string php. Смотреть фото get number from string php. Смотреть картинку get number from string php. Картинка про get number from string php. Фото get number from string php

Extracting numbers from a string in PHP.

As you can see, we were able to extract the integers from our string by using PHP’s preg_match_all function.

But what if we also want to be able to extract decimal numbers?

Extracting decimal numbers.

To extract decimal and float numbers from a string, we will have to use a different regular expression. Otherwise, our code in the previous example will split the numbers up.

In the example above, we were able to extract both the whole number and the decimal number. If you var_dump the array, you will see the following result:

get number from string php. Смотреть фото get number from string php. Смотреть картинку get number from string php. Картинка про get number from string php. Фото get number from string php

As you can see, we managed to extract both the 2 and the 8.5 from our text.

Hopefully, you found the code above useful!

Источник

How to convert a string into number in PHP?

Strings in PHP can be converted to numbers (float / int / double) very easily. In most use cases, it won’t be required since PHP does implicit type conversion. There are many methods to convert string into number in PHP some of them are discussed below:

Method 1: Using number_format() Function. The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure.

Example:

Method 2: Using type casting: Typecasting can directly convert a string into float, double or integer primitive type. This is the best way to convert a string into number without any function.

Example:

Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively.

Example:

Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly.

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

Источник

Как преобразовать строку в число в PHP?

29 ответов:

обычно вам не нужно этого делать, так как PHP будет принуждать тип для вас в большинстве случаев. Для ситуаций, когда вы хотите явно преобразовать тип,cast это:

есть несколько способов сделать это:

приведите строки к числовым примитивным типам данных:

выполнение математических операций над строками:

на любом (слабо типизированном) языке вы всегда можете привести строку к числу, добавив к ней ноль.

однако, в этом очень мало смысла, так как PHP будет делать это автоматически во время использования этой переменной, и он будет приведен к строке в любом случае во время вывода.

обратите внимание, что вы можете сохранить пунктирные числа в виде строк, потому что после приведения к плаванию он может быть изменен непредсказуемо, из-за природы чисел с плавающей точкой.

или вы можете использовать:

немного грязно, но это работает.

можно использовать (int)_value_ например.

In PHP можно использовать intval(string) or floatval(string) функции для преобразования строк в числа.

вы всегда можете добавить ноль к нему!

просто небольшое примечание к ответам, которые могут быть полезны и безопаснее в некоторых случаях. Вы можете сначала проверить, действительно ли строка содержит допустимое числовое значение, а затем преобразовать его в числовой тип (например, если вам нужно манипулировать данными, поступающими из БД, которая преобразует ints в строки). Вы можете использовать is_numeric() а то floatval() :

Я обнаружил, что в JavaScript простой способ преобразовать строку в число, чтобы умножить его на 1. Он решает проблему конкатенации, потому что символ » + «имеет несколько применений в JavaScript, в то время как символ» * » предназначен исключительно для математического умножения.

основываясь на том, что я видел здесь в отношении PHP, автоматически готов интерпретировать строку, содержащую цифры, как число (и комментарии о добавлении, поскольку в PHP » + » является чисто математическим добавлением), этот трюк с умножением отлично работает и для PHP.

Я проверил его, и он действительно работает. Хотя в зависимости от того, как вы приобрели строку, вы можете применить к ней функцию trim (), прежде чем умножать на 1.

вот функция, которую я написал, чтобы упростить вещи для себя:

Он также возвращает сокращенные версии boolean, integer, double и real.

вызывая тип с parseNumeric установленным в true преобразует числовые строки перед проверкой типа.

Тип («5», true) вернет int

тип («3.7», true) вернет float

тип(«500») вернет строку

только будьте осторожны, так как это своего рода метод ложной проверки, и ваша фактическая переменная все равно будет строкой. Вам нужно будет преобразовать фактическую переменную в правильный тип, если это необходимо. Мне просто нужно было проверить, должна ли база данных загружать идентификатор элемента или псевдоним, таким образом, не имея никаких неожиданных эффектов, так как он будет проанализирован как строка во время выполнения в любом случае.

Edit

Если вы хотите определить, являются ли объекты функциями, добавьте этот случай к коммутатору:

кроме Boykodev ответ я предлагаю следующее:

вы можете использовать это для преобразования строки в int в PHP.

но лучшим решением является использование:

попробуйте использовать что-то вроде этого:

вы можете изменить тип данных следующим образом

по историческим причинам «double» возвращается в случае float.

для вашего конкретного случая вы можете просто умножить на 1, чтобы преобразовать строку в число в php. PHP заботится о плавающей и целочисленной автоматически.

PHP сделает это за вас в пределах

Источник

PHP Numbers

In this chapter we will look in depth into Integers, Floats, and Number Strings.

PHP Numbers

One thing to notice about PHP is that it provides automatic data type conversion.

So, if you assign an integer value to a variable, the type of that variable will automatically be an integer. Then, if you assign a string to the same variable, the type will change to a string.

This automatic conversion can sometimes break your code.

PHP Integers

An integer is a number without any decimal part.

Note: Another important thing to know is that even if 4 * 2.5 is 10, the result is stored as float, because one of the operands is a float (2.5).

Here are some rules for integers:

PHP has the following predefined constants for integers:

PHP has the following functions to check if the type of a variable is integer:

Example

Check if the type of a variable is integer:

PHP Floats

A float is a number with a decimal point or a number in exponential form.

2.0, 256.4, 10.358, 7.64E+5, 5.56E-5 are all floats.

The float data type can commonly store a value up to 1.7976931348623E+308 (platform dependent), and have a maximum precision of 14 digits.

PHP has the following predefined constants for floats (from PHP 7.2):

PHP has the following functions to check if the type of a variable is float:

Example

Check if the type of a variable is float:

PHP Infinity

A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.

PHP has the following functions to check if a numeric value is finite or infinite:

However, the PHP var_dump() function returns the data type and value:

Example

Check if a numeric value is finite or infinite:

PHP NaN

NaN stands for Not a Number.

NaN is used for impossible mathematical operations.

PHP has the following functions to check if a value is not a number:

However, the PHP var_dump() function returns the data type and value:

Example

Invalid calculation will return a NaN value:

PHP Numerical Strings

The PHP is_numeric() function can be used to find whether a variable is numeric. The function returns true if the variable is a number or a numeric string, false otherwise.

Example

Check if the variable is numeric:

Note: From PHP 7.0: The is_numeric() function will return FALSE for numeric strings in hexadecimal form (e.g. 0xf4c3b00c), as they are no longer considered as numeric strings.

PHP Casting Strings and Floats to Integers

Sometimes you need to cast a numerical value into another data type.

The (int), (integer), or intval() function are often used to convert a value to an integer.

Источник

PHP Strings

A string is a sequence of characters, like «Hello world!».

PHP String Functions

In this chapter we will look at some commonly used functions to manipulate strings.

The PHP strlen() function returns the length of a string.

Example

Return the length of the string «Hello world!»:

The PHP str_word_count() function counts the number of words in a string.

Example

Count the number of word in the string «Hello world!»:

The PHP strrev() function reverses a string.

Example

Reverse the string «Hello world!»:

The PHP strpos() function searches for a specific text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.

Example

Search for the text «world» in the string «Hello world!»:

Tip: The first character position in a string is 0 (not 1).

The PHP str_replace() function replaces some characters with some other characters in a string.

Example

Replace the text «world» with «Dolly»:

Complete PHP String Reference

For a complete reference of all string functions, go to our complete PHP String Reference.

The PHP string reference contains description and example of use, for each function!

PHP Exercises

We just launched
W3Schools videos

COLOR PICKER

get number from string php. Смотреть фото get number from string php. Смотреть картинку get number from string php. Картинка про get number from string php. Фото get number from string php

LIKE US

Get certified
by completing
a course today!

CODE GAME

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials

Top References

Top Examples

Web Courses

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *