文字列を操作する関数
<?php $str = "Lee Byung Hun"; $new_str = strtolower($str); print $str; print "<br />\n"; print $new_str; ?>
Lee Byung Hun lee byung hun
<?php $str = "lbh"; $new_str = strtoupper($str); print "We love " . $new_str ; ?>
We love LBH
文字列の前後から半角スペースや改行(\n)などの空白や改行を取り除く
参考: | 先頭 | rtrim()関数、chop()関数 |
末尾 | itrim()関数 |
<?php $str = " We love LBH.\n"; $clean = trim($str); print $str; print "<br />\n"; print $clean; ?>
We love LBH. We love LBH.
※違いが表れない!
デリミタが1種類のときは正規表現を使わずに文字列を分割できる
$str1 = "fine|clowdy|rainy"; $array1 = exlode("|2, $str1); ・・・@ $str2 = implode(",", $array1); ・・・A
<?php $str1 = "I like yoga."; $str2 = str_replace("yoga", "spa", $str1); print $str1; print "<br />\n"; print $str2; ?>
I like yoga. I like spa.
$str = "I like yoga nad hiphop."; $sports = array("yoga", "hiphop"); $heauty = array("spa", "sauna"); $newstr = str_replace($sports, $beauty, $str);
※うまくいかない
<?php $str = "<U><B>PHP</B></U>"; $new_str = strip_tags($str, "<U>"); print $str; print "<br />\n"; print $new_str; ?>
HTML:<U><B>PHP</B></U> → <U>PHP</U>
PHP PHP
<?php $str = "PHP\nSQLite\n"; $new_str = nl2br($str); print $str; print "<br />\n"; print $new_str; ?>
PHP SQLite PHP SQLite
<?php $tag = "<b>\"PHP\"</b>"; $new_tag = htmlspecialchars($tag, ENT_NOQUOTES); print $tag; print "<br />\n"; print $new_tag; ?>
HTML☆ここわからない!表示の仕方を考える
"PHP"
<b>"PHP"</b>
画面表示
"PHP"
<b>"PHP"</b>
<?php $tag = "<b>\"PHP\"</b>"; $old_tag = htmlspecialchars_decode($tag); print $tag; print "<br />\n"; print $old_tag; ?>
HTML☆ここわからない!表示の仕方を考える
<b>"PHP"</b>
"PHP"画面表示
<b>"PHP"</b>
"PHP"
<?php $val1 = 712.197; $val2 = sprintf("%d", $val1); $val3 = sprintf("%f", $val1); $val4 = sprintf("%s", $val1); print $val1."<br />\n"; print $val2."<br />\n"; print $val3."<br />\n"; print $val4."<br />\n"; ?>
%d | 10進数の整数を作成する |
%f | 浮動小数点数を作成する |
%s | 文字列を作成する |
712.197 712 712.197000 712.197
<?php $str = "7月12日"; $length1 = strlen($str); $length2 = mb_strlen($str); print "「".$str."」は、半角".$length1."文字分です。"; print "
\n"; print "「".$str."」は、".$length2."文字の文字列です。"; ?>
「7月12日」は、半角7文字分です。 「7月12日」は、5文字の文字列です
<?php @$place = strpos("Byung Hun", "u", 2); print $place; print "
\n"; A$place2 = strpos("Byung Hun", "u", 4); print $place2; ?>
「u」を探す @文字列"Byung Hum"の2番目「y」以降について「u」を探して、先頭から何番目かを数える ⇒2番目 A文字列"Byung Hum"の4番目「n」以降について「u」を探して、先頭から何番目かを数える ⇒7番目
2 7
<?php $place = strrpos("Byung Hun", "g", 2); print $place; ?>
「g」を探す 文字列"Byung Hum"の2番目「y」以降についてうしろから「g」を探して、先頭から何番目かを数える ⇒4番目
4
<?php $str = substr("Byung Hun", 0, 5); print $str; ?>
文字列の0番目「B」から5文字文を取り出す。
Byung
<?php $str = substr("こんにちは", 0, 4); print $str; ?>
2文字(4バイト)が取り出される。
こん前へ 次へ