1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
/** -------------------------------------------------------------------------------
 *   string関数の文字列内の文字置換、スペース削除、文字取得、文字列長関数:利用の例
 *   「str_replace,str_repeat,trim,substr,mb_substr,strlen,mb_strlen」
 *  2015.08.19 作成 yoshi of CXMedia Inc.
 * -------------------------------------------------------------------------------- */
header("Content-type:text/plain; charset=UTF-8");

// 元の文章
$strBuff  "フルーツが好きなので、今日、".date("Y年m月d日")."に";
$strBuff .= "メロンとスイカのセットである520円のスイーツを自宅用に購入しました。";
echo 
"■元の文章\n$strBuff\n";

/* ----------------------------------------------------
 *   str_replace(文字列の置換、対象は文字列と配列)
 *  [count]:マッチして置換した数
 *----------------------------------------------------- */
//単体文字列を置換
echo "■文字列を置換( 自宅=> オフィス):str_replace(search,replace,subject [,count])\n";
$strBuffstr_replace("自宅""オフィス"$strBuff);
echo 
"$strBuff\n";

//配列の置換
echo "■配列で置換(メロン => アイス、スイカ => チョコ)\n";
$before = array("メロン","スイカ");
$after = array("アイス","チョコ");
$strBuffstr_replace($before $after$strBuff);
echo 
"$strBuff\n";

/* ----------------------------------------
 *    str_repeat関数(文字列を反復させる)
 *----------------------------------------- */
echo "■文字列を反復させる:str_repeat(string,repeat_num)\n";
$rep str_repeat(" *=* ",15);
echo 
"$rep\n";
echo 
"$strBuff\n";
echo 
"$rep\n";

/* ----------------------------------------------------------------------------
 *   trim関数(文字列から先頭と文末の空白文字を除去)
 *   空白文字は、[character_mask]で、
 * 「 」「\t」「\n」「\r」「\0」(null)「\x0B」(垂直タブ)の指定が可能
 *   全ての文字をリスト化、「..」の文字の範囲の指定も可能
 *----------------------------------------------------------------------------- */
echo "■文字列から先頭と文末の空白文字を除去:trim(string [,character_mask])\n";
echo 
"【" .$rep ."】\n";
echo 
"【" .trim($rep) ."】\n";

/* --------------------------------------------------------------------
 *   substr(文字列の一部取得)、mb_substr(日本語の文字列用)
 * 注)substrは、UTF-8コードを利用しているため、全角が3文字であることを認識
 *--------------------------------------------------------------------- */
//頭から全角8文字分出力
echo "■頭から全角8文字分出力:substr(string,start [,length])\n";
echo 
substr($strBuff,0,24) ."\n";

// 終わりから全角5文字分出力
echo "■終わりから全角5文字分出力:substr(string,負のstart)\n";
echo 
substr($strBuff,-15) ."\n";

// 日本語文字列置換:mb_substr(string,start [,length [,encoding]])
echo "■日本語:頭から全角8文字分出力:mb_substr(string,start [,length [,encoding]])\n";
echo 
mb_substr($strBuff,0,8),"\n";

/* -----------------------------------------
 *    strlen関数(文字列の長さ)とmb_strlen
 *------------------------------------------ */
echo "■関数(文字列の長さ:strlen(string); mb_strlen(string);\n";
echo 
"この文章の長さ[strlen]は" .strlen($strBuff) ."(バイト)\n";
echo 
"この文章の長さ[mb_strlen]は" .mb_strlen($strBuff) ."(文字)\n";
?>