PHP Conference Japan 2024

str_repeat

(PHP 4, PHP 5, PHP 7, PHP 8)

str_repeat重複一個字串

說明

str_repeat(字串 $string, 整數 $times): 字串

傳回重複 times 次的 string 字串。

參數

string

要重複的字串。

times

string 字串應重複的次數。

times 參數必須大於或等於 0。如果 times 設為 0,函式將會返回空字串。

回傳值

返回重複的字串。

範例

範例 #1 str_repeat() 範例

<?php
echo str_repeat("-=", 10);
?>

上述範例將輸出:

-=-=-=-=-=-=-=-=-=-=

另請參考

新增筆記

使用者貢獻的筆記 4 則筆記

Damien Bezborodov
15 年前
這是一個用分隔符號將字串重複多次的簡單單行指令

<?php
implode
($separator, array_fill(0, $multiplier, $input));
?>

範例程式碼
<?php

// 我喜歡使用標準 PHP 函式重複字串的方式
$input = 'bar';
$multiplier = 5;
$separator = ',';
print
implode($separator, array_fill(0, $multiplier, $input));
print
"\n";

// 比方說,這在我們想要在 SQL 查詢中使用 count() 計算陣列元素數量時很方便,例如 'WHERE foo IN (...)'
$args = array('1', '2', '3');
print
implode(',', array_fill(0, count($args), '?'));
print
"\n";
?>

範例輸出
bar,bar,bar,bar,bar
?,?,?
Alexander Ovsiyenko
6 年前
https://php.dev.org.tw/manual/en/function.str-repeat.php#90555

Damien Bezborodov,是的,但是你的解決方案的執行時間比 str_replace 慢 3-5 倍。

<?php

函數 spam($number) {
返回
str_repeat('test', $number);
}

函數
spam2($number) {
返回
implode('', array_fill(0, $number, 'test'));
}

//echo spam(4);
$before = microtime(true);
對於 (
$i = 0; $i < 100000; $i++) {
spam(10);
}
顯示
microtime(true) - $before , "\n"; // 0.010297
$before = microtime(true);
對於 (
$i = 0; $i < 100000; $i++) {
spam2(10);
}
顯示
microtime(true) - $before; // 0.032104
claude dot pache at gmail dot com
15 年前
這是 Kees van Dieren 函數的簡化版本,而且與 str_repeat 的語法相容

<?php
函數 str_repeat_extended($input, $multiplier, $separator='')
{
返回
$multiplier==0 ? '' : str_repeat($input.$separator, $multiplier-1).$input;
}
?>
匿名
13 年前
嗨,各位
我遇到這個例子
<?php

$my_head
= str_repeat("°~", 35);
顯示
$my_head;

?>

所以,長度應該是 35x2 = 70 !!!
如果我們顯示它

<?php
$my_head
= str_repeat("°~", 35);
顯示
strlen($my_head); // 105
顯示 mb_strlen($my_head, 'UTF-8'); // 70
?>

小心處理字元,並嘗試使用 mb_* 套件來確保一切順利...
To Top