Accessibility Tools

การแปลงสายอักขระที่เป็น attribute ให้อยู่ในรูปแบบอาร์เรย์

การแปลงสายอักขระที่เป็น attribute ให้อยู่ในรูปแบบอาร์เรย์

หากเราต้องการเขียนโค้ดเพื่อแปลงสายอักขระที่เป็น attribute (อาจจะมาจากแท็กของ html หรืออื่นๆ) ให้เป็นอาร์เรย์ เพื่อให้ง่ายต่อการนำไปใช้งาน สามารถใช้ฟังก์ชั่น parseAttributes ด้านล่างนี้นะครับ ตัวอย่างสายอักขระอาจจะมาในรูปแบบดังต่อไปนี้
$str = "width=400 height=300"
$str = "color="#dddddd""



function parseAttributes($str) {
		$pattern = '/(\\w+)\s*=\\s*("[^"]*"|\'[^\']*\'|[^"\'\\s>]*)/';
		$matches = array();
		preg_match_all($pattern, $str, $matches, PREG_SET_ORDER);
		$attrs = array();
		foreach ($matches as $match) {
			if (($match[2][0] == '"' || $match[2][0] == "'") && $match[2][0] == $match[2][strlen($match[2])-1]) {
				$match[2] = substr($match[2], 1, -1);
			}
			$name = strtolower($match[1]);
			$value = html_entity_decode($match[2]);
			switch ($name) {
			case 'class':
				$attrs[$name] = preg_split('/\s+/', trim($value));
				break;
			case 'style':
				// parse CSS property declarations
				break;
			default:
				$attrs[$name] = $value;
			}
		}
		return $attrs;
	}

 

 

php