In PHP, I have an array of variables that are ALL strings. Some of the values stored are numeric strings with commas.
What I need:
A way to trim the commas from strings, and ONLY do this for numeric strings. This isn't as straightforward as it looks. The main reason is that the following fails:
$a = "1,435";
if(is_numeric($a))
$a = str_replace(',', '', $a);
This fails because $a = "1435" is numeric. But $a = "1,435" is not numeric. Because some of the strings I get will be regular sentences with commas, I can't run a string replace on every string.
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
It sounds like the ideal solution for what you're looking for is filter_var():
$a = filter_var($a, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
(Note that it's using FILTER_VALIDATE_FLOAT instead of FILTER_VALIDATE_INT because that one doesn't currently have a FILTER_FLAG_ALLOW_THOUSAND option).
Try this .this worked for me
number_format(1235.369,2,'.','')
if you use number_format like this
number_format(1235.369,2) answer will be 1,235.37
but if you use like below
number_format(1235.369,2,'.','') answer will be 1235.37
it's removing the "," of "1,235.37"
function cleanData($a) {
if(is_numeric($a)) {
$a = preg_replace('/[^0-9,]/s', '', $a);
}
return $a;
}
If you want to remove commas from numbers inside a string that also contains words, the easiest way I think would be to use preg_replace_callback:
Example:
$str = "Hey hello, I've got 12,500 kudos for you, spend it well"
function cleannr($matches)
{
return str_replace("," , "" , $matches["nrs"]);
}
$str = preg_replace_callback ("/(?P<nrs>[0-9]+,[0-9]+)/" , "cleannr" , $str);
Output:
"Hey hello, I've got 12500 kudos for you, spend it well"
In this case the pattern (regex) differs from the one given in the accepted answer since we don't want to remove the other commas (punctuation).
If we'd use /[0-9,]+/ here instead of /[0-9]+,[0-9]+/ the output would be:
"Hey hello I've got 12500 kudos for you spend it well"
How about this:
/**
* This will parse the money string
*
* For example 1, 234, 456.00 will be converted to 123456.00
*
* #return
*/
function parseMoney(string $money) : float
{
$money = preg_replace('/[ ,]+/', '', $money);
return number_format((float) $money, 2, '.', '');
}
Example;
parseMoney('-1, 100, 000.01'); //-1100000.01
Related
I want to find a number in a string, add one to it, and replace it. These don't work:
$new_version =
preg_replace("/str\/(\d+)str/", "str/".("$1"+1)."str", $original);
$new_version =
preg_replace("/str\/(\d+)str/", "str/".(intval("$1")+1)."str", $original);
Where 'str' is a very identifiable string, each side of the number (and does not contain numbers).
I realise I can do this in more than one line of code quite easily but it seems like this should be possible.
Using a callback function allows you to cast a match to number and increment, e.g.:
preg_replace_callback(
"/str\/(\d+)str/",
function($matches) { return "str/" . ((int)$matches[1] + 1) . "str"; },
$original
);
Solely using str_replace you can get the number from the string, add one to it, and the replace the old number with the new one :
$str = 'In My Cart : 11 items';
$nb = preg_replace('/\D/', '', $str);
$nb += 1;
$str = str_replace($nb-1, $nb, $str);
echo $str;
i have a string in the format ["gated","gas"] i want this to be in the format as : gated,gas.
for this i have used str_replace function and i also get the required output but i want some alternate to do this task.
$newArray['Ameneties'] = ["gated","gas"] this is a string not an array
$a = str_replace('"', '',$newArray['Ameneties']);
$b = str_replace('[', '',$a);
$c = str_replace(']', '', $b);
echo $c;
i got the right output but i think there should be correct way of doing this as i have used the str_replace multiple times
One quick way is to json_decode and implode
echo implode( ",", json_decode( '["gated","gas"]' ));
This will return to:
gated,gas
You can replace string more than 1,
$string = str_replace(array('[', '"', ']'), '', '["gated","gas"]');
echo $string; // Output: gated,gas
Docs : str_replace
I'm having this:
$a = "t4.length = "50" AND t4.type = "F" AND (t3.minutes*60*1000+t3.seconds*1000+t3.milliseconds) < 22000";
I want to replace this string with other string, I tried str_replace but this function doesn't replace this string.
I'm trying this.
$c = str_replace($a , '', $b);
Wrong code
$c = str_replace($b , '', $a);
$b is key to find and replace
'' is replacement
$a is subject to replace
http://php.net/manual/en/function.str-replace.php
It was my fault, there were other extra spaces that's why this function was not working. I truncated all extra spaces then it was working fine.
I have a string like this:
$string = 'e.g. 25.32';
I want to pull out only the number (25.32)
The text surrounding the number could potentially be any non-number.
You could use something like :
<?php
$str = "e.g. 25";
$val = (int)$str;
?>
But it's not the best solution.
A "stronger" and universal alternative is...
Code : (UPDATED)
<?php
$str = "e.g. 25.32";
preg_match("/([0-9]+[\.,]?)+/",$str,$matches);
$val = $matches[0];
echo $val;
?>
Output :
25.32
As a function : (UPDATED)
<?php
function getInt($str)
{
preg_match("/([0-9]+[\.,]?)+/",$str,$matches);
return $matches[0];
}
?>
Usage :
<?php
$val = getInt("e.g. 25.32");
?>
If the number is simple:
([0-9]+(?:\.[0-9]+)?)
You then want to match this at the end of the string:
$string = 'e.g. 25.32';
$number = preg_replace('~^.*?([0-9]+(?:\.[0-9]+)?)$~', '$1', $string);
This will make $number contain "25.32", convert it to float if you need the float value:
$float = (float) $number;
This code does only work if there actually is a number. If you can't be sure it is, test first:
$string = 'e.g. 25.32';
$number = NULL;
$hasNumber = preg_match('~([0-9]+(?:\.[0-9]+)?)$~', $string, $matches);
if ($hasNumber)
{
list(, $number) = $matches;
}
If the number can be a number as in PHP:
([+-]?INF|[+-]?(([0-9]+|([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*))|([0-9]+|(([0-9]*[\.][0-9]+)|([0-9]+[\.][0-9]*)))[eE][+-]?[0-9]+))
So take care what you actually need to match.
You could use regular expressions if you know the format of your string with preg_match
My old function that also works with negative numbers:
function getNumber($str){
return floatval(preg_replace('/^[^\d-]+/','',$str));
}
I have a small problem. I am tryng to convert a string like "1 234" to a number:1234
I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1).
If anyone has an ideea, I'd be greatefull! Thank you!
This is how I would handle it...
<?php
$string = "Here! is some text, and numbers 12 345, and symbols !£$%^&";
$new_string = preg_replace("/[^0-9]/", "", $string);
echo $new_string // Returns 12345
?>
intval(preg_replace('/[^0-9]/', '', $input))
Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable.
That is why first answer is still str_replace.
$iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);
$str = "1 234";
$int = intval(str_replace(' ', '', $str)); //1234
I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had...
So I made this function (the idea popped in my mind thanks to Dan) :
function customCastStringToNumber($stringContainingNumbers, $decimalSeparator = ".", $thousandsSeparator = " "){
$numericValues = $matches = $result = array();
$regExp = null;
$decimalSeparator = preg_quote($decimalSeparator);
$regExp = "/[^0-9$decimalSeparator]/";
preg_match_all("/[0-9]([0-9$thousandsSeparator]*)[0-9]($decimalSeparator)?([0-9]*)/", $stringContainingNumbers, $matches);
if(!empty($matches))
$matches = $matches[0];
foreach($matches as $match):
$numericValues[] = (float)str_replace(",", ".", preg_replace($regExp, "", $match));
endforeach;
$result = $numericValues;
if(count($numericValues) === 1)
$result = $numericValues[0];
return $result;
}
So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float.
One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.
Use this code for removing any other characters like .,:"'\/, !##$%^&*(), a-z, A-Z :
$string = "This string involves numbers like 12 3435 and 12.356 and other symbols like !## then the output will be just an integer number!";
$output = intval(preg_replace('/[^0-9]/', '', $string));
var_dump($output);