PHP count, add colons every 2 characters - php

I have this string
1010081-COP-8-27-20110616214459
I need to count the last 6 characters starting from the end of this string (because it could may be long starting from the begin)
Then I need to add colons after every 2 characters.
So after counting 6 characters from the end it will be
214459
After having added the colons it will look like:
21:44:59
Can you help me achieving it?
I do not really know where to start!
Thank you

You can do this with substr, str_split and implode
The code is done on multiple lines for clarity, but can easily be done in a chain on one line:
$str = '1010081-COP-8-27-20110616214459';
//Get last 6 chars
$end = substr($str, -6);
//Split string into an array. Each element is 2 chars
$chunks = str_split($end, 2);
//Convert array to string. Each element separated by the given separator.
$result = implode(':', $chunks);

echo preg_replace('/^.*(\d{2})(\d{2})(\d{2})$/', '$1:$2:$3', $string);
It looks to me though like that string has a particular format which you should parse into data. Something like:
sscanf($string, '%u-%3s-%u-%u-%u', $id, $type, $num, $foo, $timestamp);
$timestamp = strtotime($timestamp);
echo date('Y-m-d H:i:s', $timestamp);

If you just want the time:
$time = rtrim(chunk_split(substr($s,-6),2,':'),':');

$final = "1010081-COP-8-27-20110616214459";
$c = substr($final, -2);
$b = substr($final, -4, 2);
$a = substr($final, -6, 2);
echo "$a:$b:$c";

Related

Place space or dash between number

I have number 123456789.
I want to place - between two number till my given number count would not be end.
$nubmer = 1234567890.
output will be 12-34-56-78-90
function splitNum($num) {
return implode("-", str_split($num, 2));
}
echo splitNum("1234567890") //output: 12-34-56-78-90
Check the Manual for information on str_split and join
<?php
$number = 1234567890;
$split = str_split($number,2);
echo join('-',$split);
?>
You can use simple one liner wordwrap - Wraps a string to a given number of characters:
<?php
$number = 1234567890;
echo wordwrap($number, 2, '-',true);
output:
12-34-56-78-90
You need to convert the number to string and split it into equal part of 2. then implode them. Conversion is not mandatory but good for perfect result.
$nubmer = "1234567890"; //OR $nubmer = 1234567890;
$arr = str_split($nubmer, 2);
echo implode("-", $arr);//12-34-56-78-90
"One-line" solution using chunk_split and trim functions:
$nubmer = "1234567890";
$splitted = trim(chunk_split($nubmer, 2, "-"), "-"); // contains "12-34-56-78-90"
http://php.net/manual/en/function.chunk-split.php

Get the last value in a comma-separated string

I have a string with numbers, stored in $numbers:
3,6,86,34,43,52
What's the easiest way to get the last value after the last comma? In this case the number 52 would be the last value, which I would like to store in a variable.
The number can vary in size, so trying:
substr($numbers, -X)
does not help me out I think.
This should work for you:
Just use strrpos() to get the position of the last comma and then use substr() to get the string after the last comma, e.g.
$str = "3,6,86,34,43,52";
echo substr($str, strrpos($str, ",") + 1);
output:
52
Just explode the string by the separator character and pick the last of the resulting tokens:
<?php
$string = '3,6,86,34,43,52';
$tokens = explode(',', $string);
echo end($tokens);
An alternative would be to use a regular expression:
<?php
$string = '3,6,86,34,43,52';
preg_match('/,([0-9]+)$/', $string, $tokens);
echo end($tokens);
Personally I have the opinion that efficiency is less important that easy of reading and understanding the code these days. Computation power is cheap, developers are expensive. That is why I would use the first approach, expect when the number of elements in the string gets big.
You can do it like this:
$numbers = "3,6,86,34,43,52";
$arr = explode(",",$numbers);
echo $arr[count($arr)-1];
I'd just explode it to an array, and get the last element:
$numbers = '3,6,86,34,43,52';
$arr = explode(',', $numbers);
echo $arr[count($arr) - 1];
A direct, single-function approach would be to trim every upto the last comma.
Code: (Demo)
$numbers = "3,6,86,34,43,52";
echo preg_replace('/.*,/', '', $numbers);
// 52

How to get part of string from the end in PHP?

I am making application where I receive a string from user. The string is concatenated with - character between them. First part of string contains alphabetic data whereas later part contains integers or floating point numbers. For example: A string might be 3 Cups Tea-5.99.I want to get the later part of string 5.99 separated by - character. How to do that? I know about PHP substr() function but that takes fixed characters to retrieve substring from. But in this case the later part will not be fixed. For example: 2 Jeans-65.99. In this case I would need last 4 characters meaning that I can't use substr() function.
Anybody with solution?
I know I would need to apply regex but I am completely novice in Regex.
Waiting for your help.
Thanks!
Simply
$result = explode('-', $string)[1];
For PHP<5.4 you'll have to use temporary variable:
$data = explode('-', $string);
$result = $data[1];
Edit
As mentioned in comments, if there is more than 1 part, that will be:
$result = array_pop(explode('-', $string));
$bits = explode('-', $inputstring);
echo $bits[1];
You can use substr() with strpos():
$str = '3 Cups Tea-5.99';
echo substr($str, strpos($str, "-") + 1);
Output:
5.99
Demo!
If data will be like this: "1-Cup tea-2.99", then
$data = "1-Cup tea-2.99";
$data = explode('-', $string);
$result = $data[count($data)-1];

PHP add colons to a string

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');

Help on parsing formatted string

I have strings:
17s 283ms
48s 968ms
The string values are never the same and I want to extract the "second" value from it. In this case, the 17 and the 48.
I'm not very good with regex, so the workaround I did was this:
$str = "17s 283ms";
$split_str = explode(' ', $str);
foreach($split_str as $val){
if(strpos($val, 's') !== false) $sec = intval($val);
}
The problem is, the character 's' exists in both split_str[0] and split_str[1], so my $sec variable keeps obtaining 283, instead of 17.
Again, I'm not very good with regex, and I'm pretty sure regex is the way to go in this case. Please assist. Thanks.
You don't even need to use regex for this.
$seconds = substr($str, 0, strspn($str, '1234567890'));
The above solution will extract all the digits from the beginning of the string. Doesn't matter if the first non-digit character is "s", a space, or anything else.
But why bother?
You can even just cast $str to an int:
$seconds = (int)$str; // equivalent: intval($str)
See it in action.
Regular expressions are definite overkill for such a simple task. Don't use dynamite to drill holes in the wall.
You could do this like so:
preg_match('/(?<seconds>\d+)s\s*(?<milliseconds>\d+)ms/', $var, $matches);
print_r($matches);
If the string will always be formatted in this manner, you could simply use:
<?php
$timeString = '17s 283ms';
$seconds = substr($timeString, 0, strpos($timeString, 's'));
?>
Well, i guess that you can assume seconds always comes before milliseconds. No need for regexp if the format is consistent. This should do it:
$parts = explode(' ', $str);
$seconds = rtrim($parts[0], 's')
echo $seconds; // 17s
This will split the string by space and take the first part 17s. rtrim is then used to remove 's' and you're left with 17.
(\d+s) \d+ms
is the right regexp. Usage would be something like this:
$str = "17s 283ms";
$groups = array();
preg_match("/(\d+)s \d+ms/", $str, $groups);
Then, your number before ms would be $groups[1].

Categories