Jump to content

Looping with the Regex


Ferdinand

Recommended Posts

If I have the following text file.

$string = 
'1)	The most important feature of spiral model is: requirement analysis. Risk management. quality management. configuration management	2)	The worst type of coupling is: Data coupling. control coupling. stamp coupling. content coupling 3)	One of the fault base testing techniques is: Unit testing. beta testing. Stress testing. mutation testing 4)	A fault simulation testing technique is: Mutation testing. Stress testing. Black box testing. White box testing 5)	RS is also known as specification of: White box testing. Stress testing. Integrated testing. Black box testing 6)	Which of these terms is a level name in the Capability Maturity Model?: Ad hoc. Repeatable. Reusable. Organized 7)	FP-based estimation techniques require problem decomposition based on?: Information domain values. project schedule. software functions. process activities 	What types of models are created during software requirements analysis?: Functional and behavioral. Algorithmic and data structure. Architectural and structural. Usability and reliability 9)	Which of the following is not an attribute of software engineering: Efficiency. Scalability. Dependability. Usability

With the Regex below that I have, How do I loop through the regex to get my code display one question at a time. When I submit, I proceed to the next one. Thank you.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
    <head>
	<style>
	style1 {font-family: "Baskerville Old Face"}
.style2 {
	font-family: "Baskerville Old Face";
	font-size: 12px;
	font-style: italic;
}
body {
	background-color: #99CC66;
}
#text_disabled{
border:0;
font-size:10pt;
color:black;
}
</style>
    <title>Question and Answer Read From Text File</title>
    </head>
    <body>
	<h3> Current Date and Time</h3>
	<p>
	<script language="javascript">
<!--
today = new Date();
document.write("The time now is: ", today.getHours(),":",today.getMinutes());
document.write("<BR>The date is: ", today.getDate(),"/",today.getMonth()+1,"/",today.getYear());
//-->
</script> 
        <form action="processor.php" method="POST">
        <b><u> QUESTIONS AND ANSWERS QUIZ</u></b> <br /><br />
<?php
$openFile = fopen("questionandanswers.txt", "r") or exit ("unable to open the text       file");
$string = fread($openFile, filesize("questionandanswers.txt"));
//Loop through each line of every question

//Regex to get from the first number to the string's end, so we ignore the Number Question... bit;
preg_match('/\d.*/', $string, $match);

//We get all the strings starting with a number until it finds another number (which will be the beginning of another question;
preg_match_all('/\d\D*/', $match[0], $results);

$qas = array(); // We prepare an array that will store the questions/answers
foreach($results[0] as $result)
{
    //Separating the question from the string with all the answers.
    list($question, $all_answers) = explode(':', $result);

    //Separating the different answers
	
    $answers_array = explode('.', $all_answers);
	
	//removes unnecesary spaces in the questions
	
    $answers_array_trimmed = array_map('trim', $answers_array);
	
    //Storing the question and the array with all the answers into the previously prepared array;
	
    $qas[] = array('question' => $question, 'answers' => $answers_array);
}
//Looping through the array and outputting all the info into a form;
        
$questionNr = 0;    
foreach($qas as $k=>$v)
    {
    echo "<input id='question{$questionNr}' style='width:40%' type='text' value='".$v['question']."' name='questions[]' >";
    echo '<br /><br />';
//Puts the answers of each question unique and in the form of radios
    foreach($v['answers'] as $answer)
        {
        echo "<input type=\"radio\" name=\"selected_answers[$questionNr]\" value=\"$answer\" />";
        echo "$answer";
        echo '<br/><br />';
        }
    $questionNr++;
    }
?>
<input name= "submit" type="submit" value="Submit Answers">&nbsp <input type="reset" value ="Clear Answers">
</form>
    </body>
</html>
Link to comment
Share on other sites

Try,

$openFile = fopen("questionandanswers.txt", "r") or exit ("unable to open the text file");

$string = fread($openFile, filesize("questionandanswers.txt"));

// match all characters sequence
preg_match_all('/[a-zA-Z.:?,-\s]+(?=\d\))/', $string, $parts);

// reindex the array starting to 1
$iOne = array_combine(range(1, count($parts[0], COUNT_RECURSIVE)), array_values($parts[0]));

//echo '<pre>'.print_r($iOne, true).'</pre>';

// count all re-index keys of that array 
$count = count($iOne);

// loop through array keys and display the results
for($i=1;$i<$count;$i++){
    
 echo $i.')'.$iOne[$i]."<br />";
 
}

Results:

 

1) The most important feature of spiral model is: requirement analysis. Risk management. quality management. configuration managemen
2) The worst type of coupling is: Data coupling. control coupling. stamp coupling. content coupling
3) One of the fault base testing techniques is: Unit testing. beta testing. Stress testing. mutation testing
4) A fault simulation testing technique is: Mutation testing. Stress testing. Black box testing. White box testing
5) RS is also known as specification of: White box testing. Stress testing. Integrated testing. Black box testing
6) Which of these terms is a level name in the Capability Maturity Model?: Ad hoc. Repeatable. Reusable. Organized
7) FP-based estimation techniques require problem decomposition based on?: Information domain values. project schedule. software functions. process activities

 

 

Link to comment
Share on other sites

Thank you for the contribution jazzman1, What I am trying to do is to read the text file line by line. But I can only proceed to the next line only after I have answered a question of the first line, progressively upto the last one. Thank you.

Link to comment
Share on other sites

Get all radio buttons into an array and then switch the answers and case radio buttons in your processor.php file.

 

Something like: (be careful with radio buttons, they contain empty strings, just trim them)

echo '<pre>'.print_r($_POST['selected_answers'][0], true).'</pre>';

switch($_POST['selected_answers'][0]) {
    
        case " requirement analysis":
            $value = '<pre>'.print_r($_POST['selected_answers'][0], true).'</pre>';
            break;
        case "Risk management":
            $value = '<pre>'.print_r($_POST['selected_answers'][0], true).'</pre>';
            break;
        case "quality management":
            $value = '<pre>'.print_r($_POST['selected_answers'][0], true).'</pre>';
            break;
        default:
            $value = "No radio has been selected for selected_answers";
    }
    
    echo $value;
Edited by jazzman1
Link to comment
Share on other sites

A lot of coding there, Thanks it also gives me an insight of what to do in my processor.php Thanks for that. But actually its not what I want to accomplish. When I use the above codes that I had before, I display the questions as a block in the browser. But now using the function 

fget () and not fread ()

I want to loop my the questions one at a time and each can be submitted in each session as I progress through all of them up to the last one. Sounds a bit complicated by thats what actually I am trying to achieve. But I am really thankful and appreciate  the efforts you are making jazzman1 to assist me crack this jazzman1.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.