文字

str_repeat

(PHP 4, PHP 5)

str_repeat重复一个字符串

说明

string str_repeat ( string $input , int $multiplier )

返回 input 重复 multiplier 次后的结果。

参数

input

待操作的字符串。

multiplier

input 被重复的次数。

multiplier 必须大于等于 0。如果 multiplier 被设置为 0,函数返回空字符串。

返回值

返回重复后的字符串。

范例

Example #1 str_repeat() 范例

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

以上例程会输出:

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

参见

  • for
  • str_pad() - 使用另一个字符串填充字符串为指定长度
  • substr_count() - 计算字串出现的次数

用户评论:

[#1] Anonymous [2011-10-23 04:51:03]

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 ...

[#2] Damien Bezborodov [2009-04-28 00:45:19]

Here is a simple one liner to repeat a string multiple times with a separator:

<?php
implode
($separatorarray_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($separatorarray_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(0count($args), '?'));
print 
"\n";
?>


Example Output:
bar,bar,bar,bar,bar
?,?,?

[#3] claude dot pache at gmail dot com [2009-02-10 02:25:20]

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=='' str_repeat($input.$separator$multiplier-1).$input;
}
?>

[#4] Alper Kaya [2007-06-30 03:09:15]

If you want to hide a part of your password, you can use this code. It's very simple and might be required in your user management panel.

<?php
$password 
"12345abcdef";
$visibleLength 4// 4 chars from the beginning

echo substr($password,0,4).str_repeat("*", (strlen($password)-$visibleLength));
?>

[#5] [2005-09-15 07:32:41]

In reply to what Roland Knall wrote:

It is much simpler to use printf() or sprintf() for leading zeros.

<?php
   printf
("%05d<br>\n",  1); // Will echo 00001
   
sprintf("%05d<br>\n",  1); // Will return 00001
?>

[#6] [2003-07-21 10:45:52]

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.

[#7] bryantSPAMw at geocities dot SPAM dot com [2001-10-25 04:16:27]

(For the benefit of those searching the website:)

This is the equivalent of Perl's "x" (repetition) operator, for eg.  str_repeat("blah", 8) in PHP does the same thing as "blah" x 8 in Perl.

上一篇: 下一篇: