1. 程式人生 > 程式設計 >PHP隨機生成中文段落示例【測試網站內容時使用】

PHP隨機生成中文段落示例【測試網站內容時使用】

本文例項講述了PHP隨機生成中文段落。分享給大家供大家參考,具體如下:

在建立網站的時候,很多時候都需要輸入一些中文的段落來填充頁面,大多數會是找一些新聞之類的來複制貼上。

以下程式碼是利用php來隨機生成一些中文段落,以便用來測試。

GBK版:

<?php
header('Content-type:text/html;charset=gbk');

function createWords($words = 128)
{
  $seperate = array(",","。","!","?",";");
  $strings = '';
  for ($i=0; $i<$words; $i++)
  {
    $strings .= chr(rand(0xB0,0xD6)).chr(rand(0xA1,0xFE));
    if (fmod($i,18) > rand(10,20))
    {
      $strings .= $seperate[rand(0,4)];
    }
  }
  return $strings;
}

$paras = rand(1,10);

$strings = '';

for($i=0; $i<$paras; $i++)
{
  $strings .= '&nbsp;&nbsp;&nbsp;&nbsp;'.createWords(rand(100,500)).'<br />';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=gbk" />
  <title>隨機生成中文段落</title>
  <style type="text/css">
    body{
      width: 960px;
      margin: 0 auto;
    }
    h1 {
      text-align: center;
    }
  </style>
</head>

<body>
  <h1>重新整理頁面可得到不同結果</h1>
  <div><?php echo $strings;?></div>
</body>

UTF8版:

<?php
function createWords($words = 128)
{
  $seperate = array(",",";");
  $strings = '';
  for ($i=0; $i<128; $i++)
  {
    $strings .= iconv('utf-16','utf-8',chr(rand(0x00,0xFF)).chr(rand(0x4E,0x99)));
    if (fmod($i,10);
$strings = '';

for($i=0; $i<$paras; $i++)
{
  $strings .= '&nbsp;&nbsp;&nbsp;&nbsp;'.createWords(rand(100,500)).'<br />';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>測試</title>
  <style type="text/css">
    body{
      width: 960px;
      margin: 0 auto;
    }
    h1 {
      text-align: center;
    }
  </style>
</head>
<body>
  <h1>重新整理頁面可得到不同結果</h1>
  <div><?php echo $strings;?></div>
</body>
</html>

更多關於PHP相關內容感興趣的讀者可檢視本站專題:《PHP編碼與轉碼操作技巧彙總》、《PHP陣列(Array)操作技巧大全》、《php字串(string)用法總結》、《php常用函式與技巧總結》及《PHP錯誤與異常處理方法總結》

希望本文所述對大家PHP程式設計有所幫助。