dsfds656545
2018-09-02 14:13
浏览 106
已采纳

如何通过PHP substr()函数覆盖/更改前导零的默认删除? [关闭]

In PHP when we do a substr() such that the resultant string should be something like 0004, PHP automatically removes the leading 0s and just gives 4.

I want to avoid this behavior. I want the leading zeroes to stay there. How can I enforce that?

Forexample the following snippet prints 4.

echo substr("100041", 1, 4); 

How can I force it to print 0004?

图片转代码服务由CSDN问答提供 功能建议

在PHP中,当我们执行 substr()时,结果字符串应该是某种东西 与 0004 一样,PHP会自动删除前导 0 ,只提供 4

我想避免这种行为。 我希望领先的零点留在那里。 我该如何强制执行?

例如,以下代码段打印 4

 <  code> echo substr(“100041”,1,4);  
   
 
 

如何强制它打印 0004

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • donglin6313 2018-09-02 14:20
    已采纳

    Who said? Php doesn't remove 0 in string...

    enter image description here

    点赞 评论
  • dongyi9298 2018-09-02 14:48

    Anyway create a own function..

    <?php
    
    function substring($data,$from,$length){
    
        $sub = "";
        $data = str_split($data);
        $i = 0;
        $l = 1;
        foreach($data as $letter){
    
            if($i >= $from && $l <= $length){
    
                $sub .= $letter;
                $l = $l+1;
            }
    
            $i = $i+1;
        }
    
        return $sub;
    } 
    
    echo substring("100041", 1, 4);
    
    ?>
    
    点赞 评论
  • doumingchen3628 2018-09-02 14:50

    It doesn't:

    var_dump(substr("100041", 1, 4));
    
    string(4) "0004"
    

    (online demo)

    As per documentation this is a 100% string function. It doesn't handle numbers in any special way.

    点赞 评论

相关推荐 更多相似问题