Is it possible to get only the suffix of a number with the NumberFormatter class in PHP.
For example:
$nf = new NumberFormatter( 'en', NumberFormatter::ORDINAL );
$out = $nf->format( 10000 );
echo $out . "\n";
Will result in: '10,000th'
I would just like: 'th', i.e. the suffix.
I don't believe that is possible with NumberFormatter, the best you could do would be to grab the last two characters:
echo substr($out, -2);
Otherwise skip NumberFormatter and find the suffix a different way
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 need to pull the date and time out of this string: some_report_20161005_1530.xml so I can reformat it to something more work-with-able. The date and time will change from file to file, but will always stay in this format: some_report_{year}{month}{day}_{24hr time}.xml
$test = 'some_report_20161005_1530.xml';
preg_match('(\d{4})(\d{2})(\d{2})_(\d{4})', $test, $test_matches);
print_r( $test_matches );
What would be the best way to accomplish this?
(Forgive my ignorance or misuse of these functions. I am by no means an expert)
If the some_report doesn't contain digits, the date and time parts are already in a good order to work in the DateTime constructor, so you can extract them with a simpler regex.
$date_time = new DateTime(preg_replace("/[^0-9]/", "", $your_string));
One simple regex approach would be to pull out the 8 and 4 digit numbers:
preg_match("/(\d{8})_(\d{4})/", $filename, $matches);
array_shift($matches);
list($date, $time) = $matches;
Working example: https://3v4l.org/npGC8
Or you could just use explode and skip the regex:
list($name1, $name2, $date, $time) = explode("_", str_replace(".","_", $filename));
Working example: https://3v4l.org/lAvTN
Then it's as simple as handing it to DateTime, such that you can manipulate or format however you want.
$dt = new DateTime($date . $time);
echo $dt->format('n/j/y h:ia'); // 10/5/16 03:30pm
$test = 'some_report_20161005_1530.xml';
echo preg_replace('#(\d{4})(\d{2})(\d{2})(_)(\d{2})(\d{2})#',
'${1}-${2}-${3}_${5}:${6}', $test) , '<br/>';
preg_match(
'#(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})(_)(?<hour>\d{2})(?<minute>\d{2})#',
$test,$test_matches);
print_r( $test_matches );
Just examples...
I have few strings where i need to extract only the prices in php (which will obviously be numerals).
The use cases are follows:
1) Rs. 23,459.45 desired output = 23459.45
2)Our best price 23,459.45 desired output = 23459.45
etc.
I gave the above use cases to give an idea that the preceding characters could be anything.
Please help!
How about:
$arr = array(
'Rs. 23,459.45 ',
'Our best price 23,459.45 ',
);
foreach($arr as $string) {
$string = preg_replace('/^.*?(\d+),?(\d{3})(\.\d{2})?.*$/', "$1$2$3", $string);
echo $string,"\n";
}
output:
23459.45
23459.45
It's:
$result = preg_replace('/[^0-9.]/', '', $string);
-but note, this will not validate numbers or provide valid result in common case since string could contain something like 'foo . bar,baz . price 20.5 with .6 discount' - end result will be not a valid number. So code above answers the question about "how to replace", but does not fit validating a number (and you've not mentioned if that is your goal).
About validating a number - such question will be ambiguous because it's not obvious how to convert ..20.5.6 (which will be result for string above). But if you need only to check that, use is_numeric() on $result, like this:
$string = 'foo . bar,baz . price 20.5 with .6 discount';
$result = preg_replace('/[^0-9.]/', '', $string);
$result = is_numeric($result)?(float)$result:null;
You can use this to validate the above strings. When this function valiadates Rs. , it will return two dots, so I used ltrim to remove the first dot.
<?php
//$s = "Rs. 23,459.45";
$s= "Our best price 23,459.45";
echo $result = ltrim(preg_replace("/[^0-9.]+/", "", $s),'.');
?>
http://codepad.org/cyH5OWyE
I am trying to find a piece of regex to remove a currency format.
I have two types of currency values. One is in USD format like 1,000.00 and other is in EUR like 1.000,00. I need to save the value in to db by removing both comma and dot like 1000.00
For example if the user enter the value in USD like 2,222.65, it need to replace to 2222.65,
if the user enter the value in EUR like 2.222,65 it also need to replace to 2222.65,
Instead of complex regex, use NumberFormatter::parse available for PHP 5 >= 5.3.0, PECL intl >= 1.0.0.
// German format
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo $fmt->parse($num)."<br>\n";
// USD format
$fmt = new NumberFormatter( 'en_US', NumberFormatter::DECIMAL );
$num = "9,876,543.012";
echo $fmt->parse($num)."<br>\n";
OUTPUT:
1234567.891
9876543.012
One soultion to match what separator in use, and change it to the one you prefere
<?php
/* split input in 3 parts: integer, separator, decimals */
if(preg_match('#^(?<integer>.*)(?<separator>[\.,])(?<decimals>[0-9]+)$#', $input, $matches))
{
/* clean integer and append decimals with your own separator */
$number = ((int) preg_replace('#[^0-9]+#', '', $matches['integer']) . '.' . $matches['decimals']
}
else
{
$number = (int) preg_replace('#[^0-9]+#', '', $input);
}
?>
Notice: I prefer to have my regexp in # insted of /, as i ofen use / inside my regexp,
if ypu prefer / you can use /[^0-9]+/ and /^(?<integer>.*)(?<separator>[\.,])(?<decimals>[0-9]+)$/
This assumes that they all have decimals, but it is the cleanest.
$str = "2,222.65";
$clean = preg_replace('/[^\d]/', '', $str);
$clean = substr($clean, 0,-2) . "." . substr($clean,-2);
Hello I have this string that will generate the time that I then insert in the db
$time=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('Gis',$time);
Now I need to readd colons to this string: :
I need it to be generated and inserted without colons, but shown in another place with colons reinserted, so that it will look like this:
13:24:09
Instead of:
132409
The same is for $todaydate = date('Ymd');
That should become then 2011-06-16
How can I do that?
Counting the words is not good, since we can have more or less types depending by the actual time and date.
Please advise
Thank you!
FOR WHO DOES NOT UNDERSTAND: this values are taken from the DB so I cannot use : date('Y-m-d'); in a values taken from the db........
The same is for $todaydate =
date('Ymd');
That should become then 2011-06-16
For this one, try :
date('Y-m-d');
Similar for your Other part.
Edit ::
For Date :
$time = "time from database";
$unixtimestamp = strtotime ( $time) ;
$date = date('Y-m-d', $unixtimestamp);
For time :
$time = strtotime("time from database");
$yourtime = date("H:i:s", $time);
The strings you supply for formatting can contain anything you'd like, so putting the dashes or semicolons there is no problem. You can even include other text, as long as any letters used in the date code are escaped with a backslash.
The entire
$time=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('Gis',$time);
could be rewritten, too. You're maing a timestamp from the current time, then giving it to date(). date uses the current time by default, so there's no need to do that to show the current time.
Here's one way:
$NowisTime=date('G:i:s');
If you are doing exactly what you say you are doing, you can count the characters starting at the end and add the characters (: and -) at the right place:
Both date('is') and date('Ymd') produce a fixed format using leading zeros so the length is always the same. You only have to compensate for the date('G') part.
So really all you have to do is chop off 2 characters from the end of the string twice and what remains is the year or the hour.
Well if you use date('his') instead and cast it as a string (so PHP doesn't interpret it as an integer and remove the possible leading zero), you can add colons by splitting the string every two numbers and then imploding it with colons.
$d = (string)date( 'his' );
echo (int)$d; //Format without colons
echo implode( ':', array_map('intval', str_split( $d, 2 ) ) );
For the second part, do the same except split the string by 4 characters and then split the second split by 2.
$d = date('Ymd');
echo $d; //Format without dashes
list($year, $second) = str_split( $d, 4 );
$parts = str_split( $second );
array_unshift( $parts, $year );
echo implode( '-', $parts );
In both situations however it would just be easier to start out with the formatted strings (with the colons and dashes) and remove them for the db.
$d = date('G:i:s');
echo $d; //With colons
echo str_replace( ':', '', $d );
$d = date('Y-m-d');
echo $d; //With dashes
echo str_replace( '-', '', $d );
When you are generating the value to store in your database, use a Unix timestamp:
$timestamp = time();
// store $timestamp in your database
That way you don't have to worry about how it looks or parsing it at all. Then, when you're ready to display it to your user, you can use:
$formattedTime = date('G:i:s', $timestamp);
which will display it in the colonated (is that even a word?) format for your users.
Couldn't you do something like :
$new = "";
for ($i = 2; $i <= strlen($NowisTime); $i+2) {
$new .= $NowisTime[$i-2] . $NowisTime[$i-1] . ":";
}
$NowisTime=date('G:i:s',$time);
$todaydate = date('Y-m-d');