Search code examples
phpstringfunctionsubstr

Best way to cut string in PHP


I don't want to know how to use substr, there are many examples. But I want to know if it is the best way to short a string? Is there a better/more professional way to do this?

For example, this is what my print_r gives me. But I only need houres and minutes.

 string(25) "2020-03-05T12:00:00+01:00"

Solution

  • You could use this piece of code :

    <?php
    
    $time = "2020-03-05T12:00:00+01:00";
    $dt = new DateTime($time);
    echo $dt->format('H:i');
    

    Doing this allows you for many advantages. You can, for instance, manipulate dates more easily (adding, substracting time intervals...) and format the result the same way.