Insert two points into the string

Asked

Viewed 914 times

2

I have the following string:

$valor = "0050";

How do I insert two points after the second house and stay this way?

00:50

3 answers

3


If what you have is

$valor = "0050";

just do it like this:

$valor = "00:50";

If what you have is a variable that has 4 unknown characters and wants to separate them just do

$valor = substr($valor, 0, 2) . ":" . substr($valor, 2);

I put in the Github for future reference.

If you don’t know the criteria there is complicated to solve, you need to decide a rule.

Documentation.

0

Another way to solve this problem is to use the function substr_replace(). What makes it work the way you want it is to report the fourth argument as zero. Thus will be added the character in the position defined in the third argument (in this example to two)

$valor = '0099';
echo substr_replace($valor, ':', 2, 0);

0

You can use the function strtotime php, formatting the time as your need:

$valor = "0050";

$time = date("H:i", strtotime($valor));

echo $time;

The result will be a string of value 00:50.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.