wp_kses_hair()


WordPressのwp_kses_hair()関数は、HTML属性とその値を解析して検証するために使用されます。この関数は通常、セキュリティの観点からHTML入力をフィルタリングする際に利用されます。

シンタックス

wp_kses_hair( string $string, array $allowed_protocols )

引数の説明:

  • $string (string) — 解析するHTML属性の文字列。
  • $allowed_protocols (array) — 許可されるプロトコルの配列。

例1: HTML属性の解析

次のコードは、wp_kses_hair()を使用してHTML属性を解析します。

<?php
$string = 'href="https://example.com" title="Example"';
$allowed_protocols = wp_allowed_protocols();
$result = wp_kses_hair( $string, $allowed_protocols );
print_r( $result );
?>

例2: 不正な属性を除去する

この例では、wp_kses_hair()を使用して許可されていない属性を削除します。

<?php
$string = 'onclick="alert(\'Hello\')" href="https://example.com"';
$allowed_protocols = wp_allowed_protocols();
$result = wp_kses_hair( $string, $allowed_protocols );
print_r( $result );
?>

例3: 属性と値の分離

属性名とその値を分離する例です。

<?php
$string = 'href="https://example.com" alt="An example link"';
$allowed_protocols = wp_allowed_protocols();
$result = wp_kses_hair( $string, $allowed_protocols );
foreach ( $result as $attr => $details ) {
    echo $attr . ': ' . $details['value'] . "\n";
}
?>

例4: 空の値を持つ属性の処理

空の値を持つ属性を処理する場合の例です。

<?php
$string = 'disabled readonly href="https://example.com"';
$allowed_protocols = wp_allowed_protocols();
$result = wp_kses_hair( $string, $allowed_protocols );
print_r( $result );
?>

例5: 許可プロトコルの変更

カスタムの許可プロトコルを設定して解析する例です。

<?php
$string = 'href="ftp://example.com" src="https://example.com/image.jpg"';
$allowed_protocols = array( 'https', 'ftp' );
$result = wp_kses_hair( $string, $allowed_protocols );
print_r( $result );
?>

注意事項:

  • この関数はwp_kses()などのセキュリティ関連関数と併用することをお勧めします。
  • 許可されていない属性や値を確実に削除するため、常に適切なプロトコルを定義してください。

関連機能: