PHP htmlentities()関数
例
一部の文字をHTMLエンティティに変換します。
<?php
$str = '<a href="https://www.w3schools.com">Go to
w3schools.com</a>';
echo htmlentities($str);
?>
上記のコードのHTML出力は(ソースの表示)になります。
<a href="https://www.w3schools.com">Go to w3schools.com</a>
上記のコードのブラウザ出力は次のようになります。
<a href="https://www.w3schools.com">Go to w3schools.com</a>
定義と使用法
htmlentities()関数は、文字をHTMLエンティティに変換します。
ヒント: HTMLエンティティを文字に戻すには、 html_entity_decode()関数を使用します。
ヒント: get_html_translation_table ()関数を使用して、htmlentities()で使用される変換テーブルを返します。
構文
htmlentities(string,flags,character-set,double_encode)
パラメータ値
Parameter | Description |
---|---|
string | Required. Specifies the string to convert |
flags | Optional. Specifies how to handle quotes, invalid encoding and the used document type. The available quote styles are:
Invalid encoding:
Additional flags for specifying the used doctype:
|
character-set | Optional. A string that specifies which character-set to use. Allowed values are:
Note: Unrecognized character-sets will be ignored and replaced by ISO-8859-1 in versions prior to PHP 5.4. As of PHP 5.4, it will be ignored an replaced by UTF-8. |
double_encode | Optional. A boolean value that specifies whether to encode existing html entities or not.
|
技術的な詳細
戻り値: | 変換された文字列を返します。ただし、文字列 パラメータに無効なエンコーディングが含まれている場合、ENT_IGNOREフラグまたはENT_SUBSTITUTEフラグのいずれかが設定されていない限り、空の文字列が返されます。 |
---|---|
PHPバージョン: | 4歳以上 |
変更ログ: | PHP 5.6-文字セット
パラメータのデフォルト値を(構成内の)デフォルトの文字セットの値に変更しました。 PHP5.4-文字セットパラメータのデフォルト値をUTF-8に変更しました。 PHP 5.4-ENT_SUBSTITUTE、ENT_DISALLOWED、ENT_HTML401、ENT_HTML5、ENT_XML1、およびENT_XHTMLを 追加しました。PHP5.3-ENT_IGNORE定数を追加しました。PHP5.2.3- double_encodeパラメーターを 追加しました。PHP4.1-文字セット パラメータを追加しました。 |
その他の例
例
一部の文字をHTMLエンティティに変換します。
<?php
$str = "Albert Einstein said: 'E=MC²'";
echo htmlentities($str, ENT_COMPAT); // Will only convert double quotes
echo "<br>";
echo htmlentities($str, ENT_QUOTES); // Converts double and single quotes
echo "<br>";
echo htmlentities($str, ENT_NOQUOTES); // Does not convert any quotes
?>
上記のコードのHTML出力は(ソースの表示)になります。
Albert Einstein said: 'E=MC²'<br>
Albert Einstein said:
'E=MC²'<br>
Albert Einstein said: 'E=MC²'
上記のコードのブラウザ出力は次のようになります。
Albert Einstein said: 'E=MC²'
Albert Einstein said: 'E=MC²'
Albert
Einstein said: 'E=MC²'
例
西ヨーロッパの文字セットを使用して、一部の文字をHTMLエンティティに変換します。
<?php
$str = "My name is Øyvind Åsane. I'm Norwegian.";
echo htmlentities($str, ENT_QUOTES, "UTF-8"); // Will only convert double quotes (not single quotes), and uses the character-set Western European
?>
上記のコードのHTML出力は(ソースの表示)になります。
<!DOCTYPE html>
<html>
<body>
My name is Øyvind Åsane. I'm Norwegian.
</body>
</html>
上記のコードのブラウザ出力は次のようになります。
My name is Øyvind Åsane. I'm Norwegian.
❮PHP文字列リファレンス