class-arr.php
2 years ago
class-attachment.php
2 years ago
class-conditional.php
2 years ago
class-db.php
2 years ago
class-html.php
2 years ago
class-param.php
2 years ago
class-str.php
2 years ago
class-url.php
2 years ago
class-wordpress.php
2 years ago
index.php
2 years ago
class-html.php
79 lines
| 1 | <?php |
| 2 | /** |
| 3 | * The HTML helpers. |
| 4 | * |
| 5 | * @since 1.0.0 |
| 6 | * @package MyThemeShop |
| 7 | * @subpackage MyThemeShop\Helpers |
| 8 | * @author MyThemeShop <admin@mythemeshop.com> |
| 9 | */ |
| 10 | |
| 11 | namespace MyThemeShop\Helpers; |
| 12 | |
| 13 | /** |
| 14 | * HTML class. |
| 15 | */ |
| 16 | class HTML { |
| 17 | |
| 18 | /** |
| 19 | * Extract attributes from a html tag. |
| 20 | * |
| 21 | * @param string $elem Extract attributes from tag. |
| 22 | * |
| 23 | * @return array |
| 24 | */ |
| 25 | public static function extract_attributes( $elem ) { |
| 26 | $regex = '#([^\s=]+)\s*=\s*(\'[^<\']*\'|"[^<"]*")#'; |
| 27 | preg_match_all( $regex, $elem, $attributes, PREG_SET_ORDER ); |
| 28 | |
| 29 | $new = []; |
| 30 | $remaining = $elem; |
| 31 | foreach ( $attributes as $attribute ) { |
| 32 | $val = substr( $attribute[2], 1, -1 ); |
| 33 | $new[ $attribute[1] ] = $val; |
| 34 | $remaining = str_replace( $attribute[0], '', $remaining ); |
| 35 | } |
| 36 | |
| 37 | // Chop off tag name. |
| 38 | $remaining = preg_replace( '/<[^\s]+/', '', $remaining, 1 ); |
| 39 | // Check for empty attributes without values. |
| 40 | $regex = '/([^<][\w\d:_-]+)[\s>]/i'; |
| 41 | preg_match_all( $regex, $remaining, $attributes, PREG_SET_ORDER ); |
| 42 | foreach ( $attributes as $attribute ) { |
| 43 | $new[ trim( $attribute[1] ) ] = null; |
| 44 | } |
| 45 | |
| 46 | return $new; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Generate html attribute string for array. |
| 51 | * |
| 52 | * @param array $attributes Contains key/value pair to generate a string. |
| 53 | * @param string $prefix If you want to append a prefic before every key. |
| 54 | * |
| 55 | * @return string |
| 56 | */ |
| 57 | public static function attributes_to_string( $attributes = [], $prefix = '' ) { |
| 58 | |
| 59 | // Early Bail! |
| 60 | if ( empty( $attributes ) ) { |
| 61 | return false; |
| 62 | } |
| 63 | |
| 64 | $out = ''; |
| 65 | foreach ( $attributes as $key => $value ) { |
| 66 | if ( true === $value || false === $value ) { |
| 67 | $value = $value ? 'true' : 'false'; |
| 68 | } |
| 69 | |
| 70 | $out .= ' ' . esc_html( $prefix . $key ); |
| 71 | if ( null === $value ) { |
| 72 | continue; |
| 73 | } |
| 74 | $out .= sprintf( '="%s"', esc_attr( $value ) ); |
| 75 | } |
| 76 | |
| 77 | return $out; |
| 78 | } |
| 79 | } |