PHP program which extracts attribute list from the custom tag. It also strips out the single and double quote if it exists around attribute value.
<?php
function parseAnswerTag($tag)
{
// input => <answer scale="10" points="7">
// ouput => ["scale"=>10, "points"=>7]
// get the answer tag and parse out the attributes of answer tag
$returningObj = array();
//get the splitted string as an array
$arr = splitByDelimiter(array('delimiter' => " ", 'string'=> $tag));
// sliced the array to just have attributes otherwise will have answer element too
foreach (array_slice($arr, 1) as $key => $value)
{
$arr[$key] = splitByDelimiter(array('delimiter' => "=", 'string'=> $value));
if(in_array('scale', $arr[$key]) or in_array('points', $arr[$key]))
{
// check to see if single or double quote exist in value of key
if(preg_match("/['\"]/",$arr[$key][1]))
{
// makes a call to strip out the quotes
$returningObj[$arr[$key][0]] = stripQuotes($arr[$key][1]);
}
}
}
// returns the associate key of attribute in the tag
return $returningObj;
}
function stripQuotes($str)
{
// input => "10"
// output => 10
// gets attribute with value and returns unquote string
var_dump(strpos($str, "'") === FALSE);
$start_point = 0;
$end_point = 0;
if(strpos($str, "'") !== FALSE)
{
$start_point = strpos($str, "'");
$end_point = strpos($str, "'", $start_point+1);
}
elseif (strpos($str, '"') !== FALSE)
{
$start_point = strpos($str, '"');
$end_point = strpos($str, '"', $start_point+1);
}
return substr($str, $start_point+1, $end_point - ($start_point+1));
}
function splitByDelimiter($input)
{
//gets a associate array with delimiter and string {text value to be splitted}, split them by passed delimiter and return them
// $input['delimiter'] => value splitted by and $input['string'] => value to be splitted
return explode($input['delimiter'], $input['string']);
}
Can you please give me some constructive suggestions so that I can improve?
scale
attribute. Is this intended? \$\endgroup\$parseAnswerTag
. Does that mean that these are the only attributes you care to parse? \$\endgroup\$