In PHP, there are several functions available to format strings for presentation.
Here are some of the most commonly used ones:
1. printf():
This function allows you to format a string using placeholders that are replaced with values at runtime. For example, you can use the %s placeholder to insert a string, or %d to insert an integer.
The syntax for printf() is as follows:
printf(format, argument1, argument2, ...)
Here, format is the string with placeholders, and the arguments are the values to be inserted.
2. sprintf():
This function is similar to printf(), but instead of outputting the formatted string to the screen, it returns the string. This allows you to store the formatted string in a variable or use it in further processing.
The syntax for sprintf() is as follows:
sprintf(format, argument1, argument2, ...)
Here, format is the string with placeholders, and the arguments are the values to be inserted.
3. number_format():
This function formats a number with grouped thousands and decimal separators. It takes a number as its argument and returns a formatted string. The syntax for number_format() is as follows:
number_format(number, decimals, decimal_separator, thousand_separator)
Here, number is the number to be formatted, decimals is the number of decimal places to display, decimal_separator is the character to use as the decimal separator (default is “.”), and thousand_separator is the character to use as the thousands separator (default is “,”).
4. str_pad():
This function pads a string with a specified character to a certain length. It takes a string, a length, and a pad character as its arguments, and returns the padded string.
The syntax for str_pad() is as follows:
str_pad(string, length, pad_string, pad_type)
Here, string is the string to be padded, length is the total length of the padded string, pad_string is the character to use for padding (default is a space), and pad_type specifies where to place the padding (default is STR_PAD_RIGHT).