在 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/zh-tw/n/288606.html