Formatting string into appropriate UTC offset - php

I have strings like:
-4:00
3:15
+8:30
I need to format them as UTC offset values like:
-0400
+0315
+0815
How can I convert the sample strings to the final strings? I know it probably uses some combo of str_replace and sprintf, but I cannot work it out.
Thanks!

This looks like a pretty simple re-formatting to me (Demo):
$offset = vsprintf('%+03d%02d', sscanf($offset, '%d:%d'));
0 is treated as positive number (+ as in +0000).

First, check if the input string matches. If it does, remove the whole matching string from the result, and if there are only two parts, the leading sign is missing. In this case, add a plus in the beginning and pad the hour to a length of 2. Finally convert that array into a string.
foreach (array('-1:50','1:50','+1:50','-12:00','12:00','+12:00') as $input) {
echo $input . ': ';
if (preg_match('/^([-+])?([1-9][0-9]?):([0-9]{2})$/DX', $input, $asMatch) === 1) {
unset($asMatch[0]);
if ($asMatch[1] === '') {
array_unshift($asMatch, '+');
}
$asMatch[2] = str_pad($asMatch[2], 2, '0', STR_PAD_LEFT);
echo implode('', $asMatch);
}
echo "\n";
}

In three steps here it is:
$offset = preg_replace('/:/','',$offset);
$offset = preg_replace('/\b(?=\d{3}$)/', '0', $offset);
$offset = preg_replace('/^(?=\d)/m', '+', $offset);
You can remove the m flag on the second regex if you are only passing one offset at a time.

A set of regex substitutions for the input formats you want to support would probably be the most readable and maintainable.

Related

How to count all the words with special characters

I have a question about a String i want to count all the characters in the string. Like if i have a string
"Hello world & good morning. The date is 18.05.2016"
You can use explode() to convert string into array and then use count() function to count length of array.
echo count(explode(' ', "Hello world & good morning. The date is 18.05.2016"))
You can try this code.
<?php
$file = "C:\Users\singh\Desktop\Talkative Challenge\base_example.txt";
$document = file_get_contents($file);
$return_array = preg_split("/[\s,]+/",$document);
echo count($return_array);
echo $document;
?>
Hopefully it will be working fine.
The 3rd parameter of str_word_count allows you to set additional characters to be counted as words:
str_word_count($document, 0, '&.0..9');
&.0..9 means it will consider &, ., and range from 0 to 9.
You can count the spaces with substr_count and add one.
echo substr_count($str, " ")+1;
// 9
https://3v4l.org/oJJkt

getting int value from comma separated number php

How do I turn a thousand-comma separated string representation of an integer into an integer value in PHP? (is there a general way to do it for other separators too?)
e.g. 1,000 -> 1000
Edit (Thanks #ghost) Ideally, decimals should be handled, but I could accept a solution that truncates at a decimal point.
If thats simple as it gets you could use filter_var():
$number = '1,000';
$number = (int) filter_var($number, FILTER_SANITIZE_NUMBER_INT);
var_dump($number);
Or
$number = '1,000.5669';
$number = (float) str_replace(',', '', $number);
var_dump($number);
You can strip a specific character using str_replace, and cast as an integer using intval. A regular expression filter can also be used to determine if the input string is formatted correctly. Here is what that code might look like:
<?php
function remove_delimiters_simple($string, $delimiter = ',') {
// Removes all instances of the specified delimiter and cast as an integer
// Comma (,) is the default delimiter
return (int) str_replace($delimiter, '', $string);
}
function remove_delimiters_advanced($string, $delimiter = ',') {
// Use preg_quote in case our delimiter is '/' for some reason
// The regular expression should match validly formatted numbers using a delimiter
// every 3 characters
$valid_format_expression = sprintf(
'/^\d{1,3}(%s\d{3})*$/',
preg_quote($delimiter, '/')
);
// If not a validly formatted number, return null
if (! preg_match($valid_format_expression, $string)) {
return null;
}
// Otherwise, return the simple value
return remove_delimiters_simple($string, $delimiter);
}
If using PHP >= 5.3, you could use numfmt_create(), like:
$fmt = numfmt_create( 'nl_NL', NumberFormatter::TYPE_INT32 );
$num = "1,000";
echo numfmt_parse($fmt, $num); //gives 1000
Note::nl_NL is the locale you used in formatting number, and it should be the same when using for numfmt_create

PHP Strip String, Convert to int

I have a STRING $special which is formatted like £130.00 and is also an ex TAX(VAT) price.
I need to strip the first char so i can run some simple addition.
$str= substr($special, 1, 0); // Strip first char '£'
echo $str ; // Echo Value to check its worked
$endPrice = (0.20*$str)+$str ; // Work out VAT
I don't receive any value when i echo on the second line ? Also would i then need to convert the string to an integer in order to run the addition ?
Thanks
Matt
+++ UPDATE
Thanks for your help with this, I took your code and added some of my own, There are more than likely nicer ways to do this but it works :) I found out that if the price was below 1000 would look like £130.00 if the price was a larger value it would include a break. ie £1,400.22.
$str = str_replace('£', '', $price);
$str2 = str_replace(',', '', $str);
$vatprice = (0.2 * $str2) + $str2;
$display_vat_price = sprintf('%0.2f', $vatprice);
echo "£";
echo $display_vat_price ;
echo " (Inc VAT)";
Thanks again, Matt
You cannot use substr the way you are using it currently. This is because you are trying to remove the £ char, which is a two-byte unicode character, but substr() isn't unicode safe. You can either use $str = substr($string, 2), or, better, str_replace() like this:
$string = '£130.00';
$str = str_replace('£', '', $string);
echo (0.2 * $str) + $str; // 156
Original answer
I'll keep this version as it still can give some insight. The answer would be OK if £ wouldn't be a 2byte unicode character. Knowing this, you can still use it but you need to start the sub-string at offset 2 instead of 1.
Your usage of substr is wrong. It should be:
$str = substr($special, 1);
Check the documentation the third param would be the length of the sub-string. You passed 0, therefore you got an empty string. If you omit the third param it will return the sub-string starting from the index given in the first param until the end of the original string.

PHP and Money, converting money to cents

So I have done a fair bit of research on how to store "money" in a database and I think the system I want to use is
Converting Money into CENTS and then storing the CENTS in a MySQL DB with a field type of DECIMAL (19,4).
My question is, IF I have an input field from the user... how do I deal with multiple input types.
IE:
$input = "1,346.54"
$input = "10,985.23"
$input = "110,400.50"
$input = "1033.44"
etc etc...
What would be the best method for converting this to CENTS? As we have to deal with 'strings' and convert them to INT, and divide by 100... Everything that I try throws issues because of the "comma" separation with the numbers.
Any thoughts or direction would be greatly appreciated.
function getMoneyAsCents($value)
{
// strip out commas
$value = preg_replace("/\,/i","",$value);
// strip out all but numbers, dash, and dot
$value = preg_replace("/([^0-9\.\-])/i","",$value);
// make sure we are dealing with a proper number now, no +.4393 or 3...304 or 76.5895,94
if (!is_numeric($value))
{
return 0.00;
}
// convert to a float explicitly
$value = (float)$value;
return round($value,2)*100;
}
Looks like there is a NumberFormatter class which provides a parseCurrency method. Have a look at http://www.php.net/manual/en/numberformatter.parsecurrency.php
The example provided is
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89 $";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
You can remove the commas like this:
$input = str_replace( ',', '', $input);
At this point, you can convert to cents by converting to a float and multiplying by 100. However, this is probably unnecessary. You would potential encounter precision issues when performing math operations, but simply storing the values in the database can be done in the original form without alteration of the value (assuming your DB tables are properly structured):
$input = (float)str_replace( ',', '', $input);
function convert_to_cents($v)
{
$v = str_replace(',','',$v);
$p = explode('.',$v);
if(strlen($p[1])<2){ $p[1] = $p[1]*10;}
return ($p[0]*100)+$p[1];
}
This converts most of the decimal currencies to their subunits.
$1,234,567.89 = 123456789
£ 1,234,567.89 = 123456789
€1.234.567,89 = 123456789
12,34 EUR = 1234
12,34 € = 1234
12,30 € = 1230
1,2 = 102
function convertDecimalCurrencyToSubUnit($str)
{
if( preg_match('/^(.+)[^\d](\d|\d\d)[^\d]*$/', $str, $m) )
return intval(preg_replace('/[^\d]/', '', $m[1]) . ( (strlen($m[2])>1) ? $m[2] : ('0' . $m[2]) ));
return 0;
}
Probably just remove the ',' and the '.' from the string, the result is the amount in cents.
You will probably need to parse the string from the back using strrpos ... If you find a comma 2 spots from the end, then its prob safe to assume its foreign currency and those are the CENTS... Once you determine that, use a regex to strip the remaining commas (after you convert the "CENTS" comma to a decimal of course) ... Now you have a normal DEC number to play with.
Use this to find the last comma in your string ... strrpos
Use this to replace the commas preg_replace
Here is a helpful regex website .. regexlib
//Finding the last comma
$yourCommaPos = strrpos($myString, ',');
if ($yourCommaPos == strlen($myString) - 2) {
//Comma is foreign currency decimal
// Replace with '.'
} else {
//Not foreign Currency so...
//Strip Commas
preg_replace(',', '', $myString);
}

How to get the last char of a string in PHP?

I need to get the last character of a string.
Say I have "testers" as input string and I want the result to be "s". how can I do that in PHP?
substr("testers", -1); // returns "s"
Or, for multibyte strings :
mb_substr("multibyte string…", -1); // returns "…"
substr($string, -1)
Or by direct string access:
$string[strlen($string)-1];
Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_* string family of functions.
As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];
From PHP 7.1 you can do this (Accepted rfc for negative string offsets):
<?php
$silly = 'Mary had a little lamb';
echo $silly[-20];
echo $silly{-6};
echo $silly[-3];
echo $silly[-15];
echo $silly[-13];
echo $silly[-1];
echo $silly[-4];
echo $silly{-10};
echo $silly[-4];
echo $silly[-8];
echo $silly{3}; // <-- this will be deprecated in PHP 7.4
die();
I'll let you guess the output.
Also, I added this to xenonite's performance code with these results:
substr() took 7.0334868431091seconds
array access took 2.3111131191254seconds
Direct string access (negative string offsets) took 1.7971360683441seconds
As of PHP 7.1.0, negative string offsets are also supported.
So, if you keep up with the times, you can access the last character in the string like this:
$str[-1]
DEMO
At the request of a #mickmackusa, I supplement my answer with possible ways of application:
<?php
$str='abcdef';
var_dump($str[-2]); // => string(1) "e"
$str[-3]='.';
var_dump($str); // => string(6) "abc.ef"
var_dump(isset($str[-4])); // => bool(true)
var_dump(isset($str[-10])); // => bool(false)
I can't leave comments, but in regard to FastTrack's answer, also remember that the line ending may be only single character. I would suggest
substr(trim($string), -1)
EDIT: My code below was edited by someone, making it not do what I indicated. I have restored my original code and changed the wording to make it more clear.
trim (or rtrim) will remove all whitespace, so if you do need to check for a space, tab, or other whitespace, manually replace the various line endings first:
$order = array("\r\n", "\n", "\r");
$string = str_replace($order, '', $string);
$lastchar = substr($string, -1);
I'd advise to go for Gordon's solution as it is more performant than substr():
<?php
$string = 'abcdef';
$repetitions = 10000000;
echo "\n\n";
echo "----------------------------------\n";
echo $repetitions . " repetitions...\n";
echo "----------------------------------\n";
echo "\n\n";
$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
$x = substr($string, -1);
echo "substr() took " . (microtime(true) - $start) . "seconds\n";
$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
$x = $string[strlen($string)-1];
echo "array access took " . (microtime(true) - $start) . "seconds\n";
die();
outputs something like
----------------------------------
10000000 repetitions...
----------------------------------
substr() took 2.0285921096802seconds
array access took 1.7474739551544seconds
As of PHP 8 you can now use str_ends_with()
$string = 'testers';
if (\str_ends_with($string, 's') {
// yes
}
Remember, if you have a string which was read as a line from a text file using the fgets() function, you need to use substr($string, -3, 1) so that you get the actual character and not part of the CRLF (Carriage Return Line Feed).
I don't think the person who asked the question needed this, but for me, I was having trouble getting that last character from a string from a text file so I'm sure others will come across similar problems.
You can find last character using php many ways like substr() and mb_substr().
If you’re using multibyte character encodings like UTF-8, use mb_substr instead of substr
Here i can show you both example:
<?php
echo substr("testers", -1);
echo mb_substr("testers", -1);
?>
LIVE DEMO
A string in different languages including C sharp and PHP is also considered an array of characters.
Knowing that in theory array operations should be faster than string ones you could do,
$foo = "bar";
$lastChar = strlen($foo) -1;
echo $foo[$lastChar];
$firstChar = 0;
echo $foo[$firstChar];
However, standard array functions like
count();
will not work on a string.
Use substr() with a negative number for the 2nd argument.$newstring = substr($string1, -1);
Siemano, get only php files from selected directory:
$dir = '/home/zetdoa/ftp/domeny/MY_DOMAIN/projekty/project';
$files = scandir($dir, 1);
foreach($files as $file){
$n = substr($file, -3);
if($n == 'php'){
echo $file.'<br />';
}
}

Categories