str_repeat

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

str_repeatRepete uma string

Descrição

str_repeat(string $string, int $times): string

Retorna a string repetida pelo número de vezes definido em times.

Parâmetros

string

A string a ser repetida.

times

Número de vezes que a string será repetida.

times deve ser maior ou igual a 0. Se o parâmetro times for 0, a função irá retornar uma string vazia.

Valor Retornado

Retorna a string repetida.

Exemplos

Exemplo #1 Exemplo de str_repeat()

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

O exemplo acima produzirá:

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

Veja Também

  • for
  • str_pad() - Preenche uma string até um determinado comprimento com outra string
  • substr_count() - Conta o número de ocorrências de uma substring

adicione uma nota

Notas Enviadas por Usuários (em inglês) 4 notes

up
42
Damien Bezborodov
16 years ago
Here is a simple one liner to repeat a string multiple times with a separator:<?phpimplode($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
5
Alexander Ovsiyenko
7 years ago
http://php.net/manual/en/function.str-repeat.php#90555Damien Bezborodov , yeah but execution time of your solution is 3-5 times worse than str_replace.<?phpfunction spam($number) {    return str_repeat('test', $number);}function spam2($number) {    return implode('', array_fill(0, $number, 'test'));}//echo spam(4);$before = microtime(true);for ($i = 0; $i < 100000; $i++) {    spam(10);}echo microtime(true) - $before , "\n"; // 0.010297$before = microtime(true);for ($i = 0; $i < 100000; $i++) {    spam2(10);}echo microtime(true) - $before; // 0.032104
up
0
claude dot pache at gmail dot com
16 years ago
Here is a shorter version of Kees van Dieren's function below, which is moreover compatible with the syntax of str_repeat:<?phpfunction str_repeat_extended($input, $multiplier, $separator=''){    return $multiplier==0 ? '' : str_repeat($input.$separator, $multiplier-1).$input;}?>
up
-1
Anonymous
13 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 ...
To Top