在 PHP 中,我们经常需要重复一个字符串。重复一个字符串时,我们可以自己写重复的程序,但是这样效率很低。PHP 提供了一个函数,可以快速地重复一个字符串,这个函数就是 str_repeat 函数。
一、什么是 str_repeat 函数
str_repeat 函数是 PHP 内置的函数,它的作用是重复一个字符串指定次数。
二、str_repeat 函数的语法
string str_repeat ( string $input , int $multiplier )
说明:str_repeat 函数有两个参数。
第一个参数 input 是要重复的字符串。
第二个参数 multiplier 是重复的次数。
实际上,这个函数很容易理解,如果我们想要重复一个字符串,只需要传入一个字符串和需要重复的次数即可。
下面的代码演示了 str_repeat 函数的用法。
// 重复输出 hello 5 次 echo str_repeat('hello', 5);
上面的代码输出结果为:
hellohellohellohellohello
三、str_repeat 函数的用法示例
3.1. 字符串重复
使用 str_repeat 函数可以轻松实现字符串的重复,如下代码所示:
// 重复输出 hello 10 次 echo str_repeat('hello', 10);
输出结果:
hellohellohellohellohellohellohellohellohellohello
3.2. 生成分隔符
使用 str_repeat 函数可以轻松生成一段分隔符,如下代码所示:
// 生成一个长度为 20 的分隔符 echo str_repeat('-', 20);
输出结果:
--------------------
3.3. 打印图案
在开发中,有时候需要打印一些图案,如下代码所示:
// 打印一个 5 行 10 列的星号矩形 for ($i=0; $i<5; $i++) { echo str_repeat('*', 10) . "
"; }
输出结果:
********** ********** ********** ********** **********
四、结束语
str_repeat 函数在开发中经常用到,因为有了它,我们可以更快速地实现一些字符串的重复和图案的打印。
代码示例:
// 重复输出 hello 5 次 echo str_repeat('hello', 5); // 生成一个长度为 20 的分隔符 echo str_repeat('-', 20); // 打印一个 5 行 10 列的星号矩形 for ($i=0; $i<5; $i++) { echo str_repeat('*', 10) . "
"; }
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/288606.html