Home >Backend Development >PHP Problem >How to add 0 if the php string is insufficient

How to add 0 if the php string is insufficient

青灯夜游
青灯夜游Original
2022-07-04 19:59:473634browse

In PHP, you can use the str_pad() function to pad the string with 0s. This function can fill a string with specified characters to a specified length. You only need to set the third parameter to "0" to fill in the missing length with 0. The syntax is "str_pad(string, specified length, '0', type )"; the parameter "type" specifies the padding direction. The value "STR_PAD_BOTH" is filled on both sides, the value "STR_PAD_LEFT" is filled with the left side, and the value "STR_PAD_RIGHT" is filled with the right side.

How to add 0 if the php string is insufficient

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer

In PHP, you can use str_pad The () function realizes filling in 0 if the string is missing.

str_pad() function can fill the string to a new length, that is, fill the string to the specified length with the specified characters.

str_pad(string,length,pad_string,pad_type)
Parameters Description
string Required . Specifies the string to be filled.
length Required. Specifies the length of the new string. If the value is less than the length of the original string, no operation is performed.
pad_string Optional. Specifies the string used for padding. The default is blank.
pad_type Optional. Specifies which side of the string to fill.

Possible values:

  • STR_PAD_BOTH - Pad both sides of the string. If it's not an even number, the right side gets extra padding.
  • STR_PAD_LEFT - Pad the left side of the string.
  • STR_PAD_RIGHT - Pad the right side of the string. This is the default.

You only need to set the third parameter pad_string to "0" to fill in the missing length with 0.

Example:

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$str="123456";
echo "原字符串:".$str."<br><br>";

echo "补位后:".str_pad($str,10,"0")."<br><br>";
echo "补位后:".str_pad($str,10,"0",STR_PAD_BOTH)."<br><br>";
echo "补位后:".str_pad($str,10,"0",STR_PAD_LEFT)."<br><br>";
?>

How to add 0 if the php string is insufficient

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to add 0 if the php string is insufficient. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn