首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在php中添加前导0

在php中添加前导0
EN

Stack Overflow用户
提问于 2012-07-26 00:27:02
回答 3查看 21.9K关注 0票数 7

我有过

  • 教程1如何使这个
  • 教程21如何使此
  • 教程2如何使这个
  • 教程3如何使这个

我需要

  • 教程01如何使此
  • 教程21如何使此
  • 教程02如何使这个
  • 教程03如何制作这个

这样我就能点好了。(在找到个位数时添加前导0)

要转换的php方法是什么?

提前感谢

注-请确保它只首先识别个位数,然后再添加前导零。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-07-26 00:32:32

如果它来自DB,那么这就是在sql查询上这样做的方法:

代码语言:javascript
复制
lpad(yourfield, (select length(max(yourfield)) FROM yourtable),'0') yourfield

这将得到表中的最大值,并放置前导零。

如果它是硬编码(PHP),使用str_pad()

代码语言:javascript
复制
str_pad($yourvar, $numberofzeros, "0", STR_PAD_LEFT);

这是我在一个在线php编译器上所做的一个很小的例子,它可以工作.

代码语言:javascript
复制
$string = "Tutorial 1 how to";

$number = explode(" ", $string); //Divides the string in a array
$number = $number[1]; //The number is in the position 1 in the array, so this will be number variable

$str = ""; //The final number
if($number<10) $str .= "0"; //If the number is below 10, it will add a leading zero
$str .= $number; //Then, add the number

$string = str_replace($number, $str, $string); //Then, replace the old number with the new one on the string

echo $string;
票数 4
EN

Stack Overflow用户

发布于 2012-07-26 00:29:09

str_pad()

代码语言:javascript
复制
echo str_pad($input, 2, "0", STR_PAD_LEFT);

sprintf()

代码语言:javascript
复制
echo sprintf("%02d", $input);
票数 11
EN

Stack Overflow用户

发布于 2022-01-11 13:01:56

如果你的目标是做自然排序,就像人类一样,为什么不直接使用strnatcmp呢?

代码语言:javascript
复制
$arr = [
    'tutorial 1 how to make this',
    'tutorial 21 how to make this',
    'tutorial 2 how to make this',
    'tutorial 3 how to make this',
];
usort($arr, "strnatcmp");
print_r($arr);

上面的示例将输出:

代码语言:javascript
复制
Array
(
    [0] => tutorial 1 how to make this
    [1] => tutorial 2 how to make this
    [2] => tutorial 3 how to make this
    [3] => tutorial 21 how to make this
)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11660683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档