Forum PHP 2017

str_repeat

(PHP 4, PHP 5, PHP 7)

str_repeat文字列を反復する

説明

string str_repeat ( string $input , int $multiplier )

inputmultiplier 回を繰り返した文字列を返します。

パラメータ

input

繰り返す文字列。

multiplier

input を繰り返す回数。

multiplier は 0 以上でなければなりません。 multiplier が 0 に設定された場合、この関数は空文字を返します。

返り値

繰り返した文字列を返します。

例1 str_repeat() の例

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

上の例の出力は以下となります。

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

参考

add a note add a note

User Contributed Notes 4 notes

up
20
Damien Bezborodov
8 years ago
Here is a simple one liner to repeat a string multiple times with a separator:

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

Example script:
<?php

// How I like to repeat a string using standard PHP functions
$input = 'bar';
$multiplier = 5;
$separator = ',';
print
implode($separator, array_fill(0, $multiplier, $input));
print
"\n";

// Say, this comes in handy with count() on an array that we want to use in an
// SQL query such as 'WHERE foo IN (...)'
$args = array('1', '2', '3');
print
implode(',', array_fill(0, count($args), '?'));
print
"\n";
?>

Example Output:
bar,bar,bar,bar,bar
?,?,?
up
3
Anonymous
5 years ago
hi guys ,
i've faced this example :
<?php

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

?>

so , the length should be 35x2 = 70 !!!
if we echo it :

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

be carefull with characters and try to use mb_* package to make sure everything goes well ...
up
0
claude dot pache at gmail dot com
8 years ago
Here is a shorter version of Kees van Dieren's function below, which is moreover compatible with the syntax of str_repeat:

<?php
function str_repeat_extended($input, $multiplier, $separator='')
{
    return
$multiplier==0 ? '' : str_repeat($input.$separator, $multiplier-1).$input;
}
?>
up
0
Anonymous
13 years ago
str_repeat does not repeat symbol with code 0 on some (maybe all?) systems (tested on PHP Version 4.3.2 , FreeBSD 4.8-STABLE i386 ).

Use <pre>
while(strlen($str) < $desired) $str .= chr(0);
</pre> to have string filled with zero-symbols.
To Top