preg_match – regular expression

Here is a good link for a cheat sheet for regular expressions that if you forget some of the syntax.

Here are some quick notes about regular expression in PHP that allow you to pull out information from a string of text.

$stringofvalues = "hi there from me - and now after that lets!!";
preg_match("/^.* - (.*)!!/", $stringofvalues, $matches);
print_r($matches);

and the output would be

Array
(
    [0] => hi there from me - and now after that lets!!
    [1] => and now after that lets
)

where the first array [0] is always the string that was passed in, and any matches that you picked are in the following index’s in the array (because the first match [0] in the array is the real string because it has matched that already 🙂 ) and then the second matches that you want to check for are within the regular expression ( .. ) brackets, so in my regular expression

/^.* - (.*)!!/

this means start at the beginning of the string ‘^’ and then any character ‘.’ 0 or more times ‘*’ find un-till you find a string as ” – ” (which is within the string to be searched) and then now copy any character 0 or more times ‘.*’ but this time place it into a matched index within the array by using the () around that regular expression search.

So if you wanted to pull back 2 matches from that string, then you could do something like

preg_match("/^(.*) - (.*)!!/", $stringofvalues, $matches);
print_r($matches);

Which the output would be

Array
(
    [0] => hi there from me - and now after that lets!!
    [1] => hi there from me
    [2] => and now after that lets
)

where the first part of the string (before the ” – “) is within the 1st index of the matches array and then the second search match is within the 2nd index of the matches array.

equals =,==,===

Since PHP does have type safe aspects to the language, for example within in c++ if you declared a variable to be of type int(eger) and other to be string and then to see if they was the same value, the compiler would complain because they are of different types so you need to convert one or the other to the same type before doing the check. Well in PHP if you had the a variable with the same value as such.

$intvalue = (int)4;
$strint = "4";

and did a test to see if they was the same in value then

if ($intvalue == $strint)
	echo "they are the same!, but one is a string and the other is a integer!";

would work since php does converts them into the same types to then do a comparison, but if you wanted to make sure that they are of the same types then use the ===

if ($intvalue=== $strint)
   echo "this should not show!!!.. because there types are different!!";
else
   echo "they may have same 'value', but they are different types so not equal";

the 3 equals (===) means compare the values and also the types, which in turn the else part of the if condition would be printed because, yes they are the “same” value but of different types and thus they are not equal.

pass by reference

When you call a function normally within PHP the variable that you pass is a copy of, for example

function doesNotAlter($alterMe)
{
   $alterMe++;
}
$pleaseAlterMe = 4;
doesNotAlter($pleaseAlterMe);

that will alter the $alterMe variable by adding one to it, but it will only alter it in a local scope of that variable so the actual variable that was passed ($pleaseAlterMe) will not change its value.

But if you pass by reference, then you bring the passing variable into the local scope of that function and thus any alternations to it will act on the variable that has been passed, the only thing that you need to alter is to add a (&), which is very similar to c/c++ which passes the reference to the object (pointer to).

function doesNotAlter(&$alterMe)
{
   $alterMe++;
}
$pleaseAlterMe = 4;
doesNotAlter($pleaseAlterMe);

The & is added to the variable in the passing function parameter list and that is all that it takes to make that remote variable to the function doesNotAlter, to now become a local scoped variable that will alter, so I could change the function name to doesAlter ;).

function doesAlter(&$alterMe)
{
   $alterMe++;
}
$pleaseAlterMe = 4;
doesNotAlter($pleaseAlterMe);
echo $pleaseAlterMe;

So now output would be “5”, because the local variable to the execution of the program is $pleaseAlterMe is first set to 4 and then passed by reference to the doesAlter me function which will actually alter that variable (by adding one to it) and then when you output that variable it will be 5.

CS75 – Assignment 0 – Three Aces Menu

I am doing the Harvards building dynamic websites called CS-75 (also could be called E-75), because someone told me about it and I just thought might as well, it is all learning 🙂 even if allot of it you may already know.

Anyway, to setup the CS75 on my personal laptop ( I am running Ubuntu 10.4) I did a couple of alternations for me so that the local apache instance looks like I am doing it under the top level domain of CS75 :).. so for this assignment Three Aces menu I am calling the website http://threeaces.cs75 on my local host, so to setup that I altered the /etc/hosts file and added

127.0.0.1       threeaces.cs75

so that local IP will also have threeaces.cs75 🙂 and now need to alter apache to allow me to run that as a virtualhost on my laptop, I added the file within

sudo vim /etc/apache2/sites-available/cs75_threeaces

with adding in

<VirtualHost *:80>
       ServerAdmin emailaddress@here.com
       ServerName  threeaces.cs75
       DocumentRoot /var/www/cs75/ass0
       <Directory /var/www/cs75/ass0>
               Options Indexes FollowSymLinks MultiViews
               AllowOverride None
               Order allow,deny
               allow from all
       </Directory>
 
       ErrorLog /var/log/apache2/error.log
       LogLevel warn
       CustomLog /var/log/apache2/access.log combined
 
</VirtualHost>

Which points to the /var/www/cs75/ass0 as the base directory for this assignment :).

I have included the assignments 0 PDF for more information, but basically this assignment is about playing with simpleXML to load in a menu (that you have created from the menu list of the restaurant Three Aces) which is in XML format, you get to pick the format, but here is mine (it has the extras link within the menu->type extras attribute which link to the extras at the bottom of the menu format)

<?xml version="1.0" encoding="ISO-8859-1"?>
<menu>
	<type name="Pizzas" extras="Extra Cheese">
		<item name="Tomato &amp; Cheese">
			<price type="Small">5.50</price>
			<price type="Large">9.75</price>
		</item>
		<item name="Onions">
			<price type="Small">6.85</price>
			<price type="Large">10.85</price>
		</item>
	</type>
	<type name="Salads">
		<item name="Garden">
			<price type="Small">3.50</price>
			<price type="Large">4.50</price>
		</item>
		<item name="Greek">
			<price type="Small">4.50</price>
			<price type="Large">5.50</price>
		</item>
	</type>
	<type name="Grinders">
		<item name="Meatless">
			<price type="Small">4.50</price>
			<price type="Large">4.95</price>
		</item>
		<item name="Hamburger">
			<price type="Small">4.50</price>
			<price type="Large">4.95</price>
		</item>
	</type>
	<type name="Special Dinners">
		<item name="Chicken Wing Dinner">
			<price>7.25</price>
		</item>
		<item name="Gyro Plate">
			<price>7.25</price>
		</item>
	</type>
	<extras name="Extra Cheese">
		<price type="Small">1.25</price>
		<price type="Large">1.85</price>
	</extras>
</menu>

You can implement it anyway that you want to, but to not have two same names of the food for different sizes. So that is why I have a the item name with the price list(s) underneath. It is only part of the menu that I implemented above.

The next part is to only have part of the menu on the main home page, so I am just displaying the main types of food options, I have included the source file for all of the files in the zip file above.

<form name="types" method="get" action="types.php">
<?php
// display the user the different types of foods that are avaible to order
$xml = simplexml_load_file("menu.xml");
// list the different types on the menu
foreach ($xml->type as $types)
{
	echo "<input type=\"radio\" name=\"type\" value=\"" .$types->attributes()->name .  "\"/>".$types->attributes()->name . "<br/>" ;
}
?>
<input type="submit"/>
</form>

Once the user has selected the type of food that they want, you next to have display the items of food within that area, so I am passing in the $_GET string from the index page the type of food, so within the types.php I pick up the type and then display all of the food items within that area. I did do some javascript that will make sure that there is a valid integer value within the, also at the start of the code I am pulling any extra values from the menu to populate the extras option.

<form name="types" method="get" action="checkout.php" onsubmit="return checkout()">
<?php
// display the different items within that type area of foods, with also there different prices and sizes
// normal = normal size for the default size
$xml = simplexml_load_file("menu.xml");
$type = $_GET["type"];
echo $type. "<table border=1>";
echo "<input type=\"hidden\" value=\"".str_replace(" ", "@",$type)."\" name=\"type\"/>";
$result = $xml->xpath("//type[@name='$type']");
if (sizeof($result[0]) == 0)
	echo "<br/><br/>Please go back to home, because cannot find that type<br/><br/>";
else
{
	$extras = $result[0]->attributes()->extras;
	if (strlen($extras) > 0)
	{
		$resultExtras = $xml->xpath("//extras[@name='$extras']");
		if (sizeof($resultExtras[0]) > 0)
		{
			$extraName = $resultExtras[0]->attributes()->name;
			for ($i=0; $i < sizeof($resultExtras[0]); $i++)
			{
				$thePrice =  $resultExtras[0]->price[$i];
				$theType = ($resultExtras[0]->price[$i]->attributes()->type ? $resultExtras[0]->price[$i]->attributes()->type : "Normal");
				$theExtras[$i] = array((string)$thePrice, (string)$theType);
			}
		}
	}
	foreach ($result[0] as $items)
	{
		echo "<tr><td>".$items->attributes()->name."</td><td>Price</td><td>Quantity</td>";
		if (strlen($extras)) echo "<td>$extras</td>";
		echo "</tr>";
		for ($i=0; $i < sizeof($items->children()); $i++)
		{
			echo "<tr><td>". $items->price[$i]->attributes()->type . 
				"</td><td>" . $items->price[$i].
				"</td><td><input type=\"text\" size=\"1\" value=\"\" name=\"".str_replace(" ", "@",$items->attributes()->name)."_".$i."\"/></td>";
			if (strlen($extras))
			{
				foreach ($theExtras as $typeCheck)
				{
					if ($typeCheck[1] == $items->price[$i]->attributes()->type)
					{
						echo "<td><input type=\"checkbox\" name=\"".str_replace(" ","_",$extras)."_".$i."\" value=\"".str_replace(" ", "@",$items->attributes()->name)."_".$i."\"/></td>";
						break;
					}
				}
			}
			echo "</tr>";
		}
	}
}?>
</table>
<input type="submit" name="submit"/>
</form>

Because there is a basket of items that the customer will like to buy, I am also storing the basket details within the $_SESSION within a multi array, the array looks like something like

Array
(
    [Pizzas] => Array
        (
            [Tomato  Cheese] => Array
                (
                    [Small] => Array
                        (
                            [price] => 5.5
                            [quantity] => 6
                        )
                )
        )
)

So in the next page, checkout.php I need to update the basket details and also then display what the customer has already picked (with giving the options to update the quantity of goods and also to remove them if they did not want it), the first part loads the new item(s) into the basket and the second part of the code below will display the basket to the user, and call the update.php file if any quantities/remove of items need to be done.

<form name="types" method="get" action="update.php">
<table>
<?php
// display the updated details of the order with the new order addon's 
// and also any previous details of the order, if you want to place the order
// click the order now link below.
$xml = simplexml_load_file("menu.xml");
// load basket from the session
$basket = $_SESSION["basket"];
$type = $_GET["type"];
$type = str_replace("@", " ", $type);
 
$result = $xml->xpath("//type[@name='$type']");
if (sizeof($result[0]) == 0)
{
	if (strlen($type) > 0)
		echo "<br/><br/>Please go back to home, because cannot find that type<br/><br/>";
}
else
{
	$extras = $result[0]->attributes()->extras;
	if (strlen($extras) > 0)
	{
		$resultExtras = $xml->xpath("//extras[@name='$extras']");
		if (sizeof($resultExtras[0]) > 0)
		{
			$extraName = $resultExtras[0]->attributes()->name;
			for ($i=0; $i < sizeof($resultExtras[0]); $i++)
			{
				$newname = str_replace(" ", "_" , $extras) . "_" . $i;
				$$newname = $_GET[$newname];
				if (strlen($$newname) > 0)
				{
					$thePrice =  $resultExtras[0]->price[$i];
					$theType = ($resultExtras[0]->price[$i]->attributes()->type ? $resultExtras[0]->price[$i]->attributes()->type : "Normal");
					$theExtras[$i] = array($$newname, (string)$thePrice, (string)$theType);
				}
			}
		}
	}
 
	foreach ($result[0] as $items)
	{
		for ($i=0; $i < sizeof($items->children()); $i++)
		{
			$newname = $items->attributes()->name."_".$i;
			$newname = str_replace(" ", "@", $newname);
			$$newname = $_GET[$newname];
			if ($$newname > 0)
			{
				$priceType = $items->price[$i]->attributes()->type;
				if (strlen($priceType) <=1)
					$priceType = "Normal";
				$extraPrice = 0;
				foreach ($theExtras as $extraAdd)
				{
					if ($extraAdd[0] == $newname)
						$extraPrice = $extraAdd[1];
				}
				$basket[(string)$type][(string)$items->attributes()->name][(string)$priceType . ($extraPrice > 0 ? (string)" (".$extras.")" : "")] = 
							array("price" =>(float) ($items->price[$i]) + (float)$extraPrice, 
									"quantity" => (int)($$newname 
										+ $basket[(string)$type][(string)$items->attributes()->name][(string)$priceType]["quantity"]) );
				// going with the theory of adding to the previous quantity
				echo "Have added " . $type . " (". $items->attributes()->name . " " . $priceType . ")<br/>";
			}
		}
	}
	$_SESSION["basket"] = $basket;
}
// lets print out the basket in a form of the user to confirm and also remove / alter the quantity
$totalPrice = 0;
echo "<table border=1><tr><td width=50>Type</td><td width=50>Item</td><td width=50>Size</td><td>Price</td><td>Quantity</td><td>Total Price</td><td>Remove</td></tr>";
foreach ($basket as $type => $typevalue)
{
	echo "<tr><td colspan=\"6\">$type</td>";
	foreach ($typevalue as $item => $itemvalue)
	{
			echo "<tr><td></td><td colspan=\"5\">$item</td></tr>";
			foreach ($itemvalue as $size => $sizevalue)
			{
				$namevalue = $type."_".$item."_".$size;
				$namevalue = str_replace(" ","@",$namevalue);
				echo "<tr><td></td><td></td><td>$size</td>";
				echo "<td>&pound;".number_format($sizevalue["price"],2) . "</td><td><input size=5 value=" . $sizevalue["quantity"]  . " name=\"".$namevalue."_quantity\"/></td><td>&pound;".number_format($sizevalue["price"] * $sizevalue["quantity"],2) ."</td><td><input type=\"checkbox\" name=\"".$namevalue."_remove\"/></td></tr>";
				$totalPrice +=$sizevalue["price"] * $sizevalue["quantity"];
			}
	}
	echo "</tr>";
}
echo "</table>";
 
echo "The total price is &pound;".number_format($totalPrice,2)."<br/>";
?>
</table>
<input type="submit"/>
</form>

here is the update.php, this will update the basket from the requested action from the above php file.

<?php
// this will update the session basket from the checkout.php page
session_start();
$xml = simplexml_load_file("menu.xml");
// load basket from the session
$basket = $_SESSION["basket"];
foreach ($_GET as $key => $value)
{
	$key = str_replace("@", " ", $key);
	list($type, $item, $size,$command) =  split("_", $key);
	if ($command== "quantity" && $value > 0)
	{
		$basket[$type][$item][$size]["quantity"] = $value;
	}
	elseif ($command =="remove")
	{
		unset($basket[$type][$item][$size]);
		// clean out the type -> item if none more left
		if (sizeof($basket[$type][$item])==0)
			unset($basket[$type][$item]);
		// clean out the type if none left
		if (sizeof($basket[$type])==0)
			unset($basket[$type]);
	}
}
$_SESSION["basket"] = $basket;
// redirect back to checkout.php
header('Location: checkout.php');
?>

and redirects back to checkout.php.

The last page displays the order in total and also says thanks very much for the order :).. and deletes the basket details :).

<table>
<?php
// display the order details and also thanks for placing the order
$basket = $_SESSION["basket"];
// lets print out the basket in a form of the user to confirm and also remove / alter the quantity
$totalPrice = 0;
echo "<table border=1><tr><td width=50>Type</td><td width=50>Item</td><td width=50>Size</td><td>Price</td><td>Quantity</td><td>Total Price</td></tr>";
foreach ($basket as $type => $typevalue)
{
	echo "<tr><td colspan=\"6\">$type</td>";
	foreach ($typevalue as $item => $itemvalue)
	{
			echo "<tr><td></td><td colspan=\"5\">$item</td></tr>";
			foreach ($itemvalue as $size => $sizevalue)
			{
				echo "<tr><td></td><td></td><td>$size</td>";
				echo "<td>&pound;".number_format($sizevalue["price"],2) . "</td><td>" . $sizevalue["quantity"]  . "</td><td>&pound;".number_format($sizevalue["price"] * $sizevalue["quantity"],2) ."</td></tr>";
				$totalPrice +=$sizevalue["price"] * $sizevalue["quantity"];
			}
	}
	echo "</tr>";
}
echo "</table>";
 
echo "The total price is &pound;".number_format($totalPrice,2)."<br/>";
session_destroy();
?>
</table>

The file above does include all of the php files from the above comments and the PDF of the assignment. You can also view the assignment live on my CS – 75 assignment 0 test area.

struct – setup and memory locations

When you setup a struct within c++, it is kinder like having a array of data and if you want to you can access the internal parts by using some memory pointer location fun!.

Lets say that you have a struct of

struct intvalue {
    int a;
    int b;
};

Just to say that since I am using int(eger) values so that is what I am incrementing by in the pointer arithmetic which is why I am casting the pointer to a integer value.

So lets say that we create a variable of intvalue and setup the values as below

intvalue testvalue;
testvalue.a = 4;
testvalue.b = 5;

We can then pull out the value of a or b, but using memcpy and just outputting to a int(eger) variable as below, the key is the ((int*)&testvalue)+1, this will first convert the testvalue variable to a pointer to memory location and then (int*) casts that pointer to a int pointer, because internally that is what it is, and then just add 1 to it, which points to the second value ( in this case the value of b which is 5)

    int avalue;
    // convert to a int pointer type and then add one to it (to the next array element as such).
    memcpy(&avalue, ((int*)&testvalue)+1,sizeof(int));
    cout << "a value (or is it the b value :) ) " << avalue << endl;

The output would be

a value (or is it the b value :) ) 5

because I am pointing to the second value which is b and thus 5 :).

Of course if you just wanted the value of first int (the value of a in this case) you do not add the 1 to the memory location, for example

    memcpy(&avalue, ((int*)&testvalue),sizeof(int));

this time I am just converting the testvalue (casting) to a int pointer and thus pointing to the start of the struct and that is where the int a variable is living :).

CS107 – Assignment 1 – Context Free Grammar – Random Sentence Generator

This is assignment 1 from a older CS107 course, because the latest course work is held on a UNIX server which in turn you need access to!!.. kinder does not help when you do not have access too!!.. Here is where I got the files from cs107 link, there is a zip file at the bottom of that page which has all of the assignments and handouts etc.

The basics of a context free grammar is (as taken from the PDF file attached which is the assignment 1 in more details), the tokens as such are the <..> parts of the block, so that you start at <start> and then you print out “The ” and then goto the <object> block to then print out a randomly picked object to then print out the <verb> if there is any blocks within the object/verb then do them before heading back to the last word on the <start> block which is “tonight”. That is it, it generates random text :).

The Poem grammar
{
<start>
	The <object> <verb> tonight. ;
}
 
{
<object>
	waves	;
	big yellow flowers ;
	slugs ;
}
 
{
<verb>
	sigh <adverb> ;
	portend like <object> ;
	die <adverb> ;
}
 
{
<adverb>
	warily ;
	grumpily ;
}

So the assignment is mainly to get used to compiling up programs within a Linux/Unix environment, I was using qt-creator IDE (which has placed some files within the zip file attached, but it does not effect the directory structure as such). To compile on Linux/Unix as long as there is a Makefile you can just

make

So, the assignment 1 base code reads in the textual files and all is required is to output the text within a random sentence and repeat 3 times, so the start of the code does the looping and calls the doRandomText function which requires as parameters the mapped (map) grammar and where to start ()

  for (int i =1;i <= 3; i++)
  {
      cout << "Version #" << i << endl << endl;
      doRandomText(grammar, "<start>");
      cout << endl << endl;
  }
  return 0;
}
 
// recursive loop in the text and produce randomly generated text
void doRandomText(map<string, Definition> theGrammar, string terminal)
{
    Definition def = theGrammar[terminal];
    assert(def.getNonterminal().size() !=0);
    Production prod = def.getRandomProduction();
    for (Production::iterator prodIter = prod.begin(); prodIter != prod.end(); prodIter++)
    {
        string theText = *prodIter;
        if (theText.at(0)=='<' && theText.at(theText.size()-1)== '>')
            doRandomText(theGrammar, theText);
        else
        {
            if (theText == "," || theText == ".")
                cout << theText;
            else
                cout << " " << theText;
        }
    }
}

The recursive function above basically tries to find the terminal within the grammar definitions and if there is not one, exit the code (assert), else print out the textual data whilst iterating over them, if there is any more terminals within the sentence then goto that terminal by calling this same function.

Here is the output of a run from the program.

./rsg assn-1-rsg-data/excuse.g 
The grammar file called "assn-1-rsg-data/excuse.g" contains 7 definitions.
Version #1
 
 I need an extension because my disk got erased, and I'm sure you've heard this before, but I had to make up a lot of documentation for the Navy in a big hurry, and I'm sure you've heard this before, but my printout was enshrowded in a mysterious fog for three days and then vanished, and I'm sure you've heard this before, but all my pencils broke, and just then I had 7 programs in like, a billion different langauges, and if you can believe it, I just didn't feel like working, and and then if I recall correctly I had to worry about the Winter Olympics, and and then if I recall correctly my disk got erased, and as if that wasn't enough I forgot how to write.
 
Version #2
 
 I need an extension because I got stuck in a blizzard at Tahoe, and then get this, my Mac was enshrowded in a mysterious fog for three days and then vanished.
 
Version #3
 
 I need an extension because I didn't know I was in this class, and then I just didn't feel like working, and I'm sure you've heard this before, but I thought I already graduated, and then, just when my mojo was getting back on its feet, the bookstore was out of erasers, and if you can believe it, I didn't know I was in this class, and and then if I recall correctly my dorm burned down.

Explicit – c++ what is it for ?

The explicit keyword in c++ is make sure that user of your class only creates and uses the class only creates it in the way that you was expecting and not via any references as such.

For example in the following code example

class mainClassWith {
public:
    // this basically will setup the internal_value equal to the value that is passed from the user
    explicit mainClassWith(int value) : internal_value(value) {} ;
 
    int internal_value;
};
 
int functionWith(const mainClassWith &theClass)
{
    cout << "the value with " << theClass.internal_value << endl;
}

The functionWith will take a parameter of mainClassWith of which has a explicit keyword on its constructor, this means that if we try and do something like

    mainClassWith mainWith(4);
 
    functionWith(mainWith);

then the compiler will compile and also the output would be printed to the screen of “the value with 4”, but since we know that the mainClassWith takes a integer value as a constructor and try to bypass any object creation of that mainClassWith and try and do this

functionWith(3);

then the compiler will complain because we cannot setup a mainClassWith on the fly like this and let the compiler pass a value of “3” to the class and hope that it works!!!, we have explicitly declared that the constructor must be initialised before using.

But if we did take off the explicit keyword as in the class example below.

class mainClassWithOut {
public:
    // this basically will setup the internal_value equal to the value that is passed from the user
    mainClassWithOut(int value) : internal_value(value) {} ;
 
    int internal_value;
};
 
int functionWithout(const mainClassWithOut &theClass)
{
    cout << "the value without  "<< theClass.internal_value << endl;
}

then we are able to call the new function (functionWithout) without actually setting up the object and allow the compiler to make up its own instance of that object and pass to the function.

functionWithout(5);

would work and the output would be “the value without 5” which is correct, but the compiler and created the mainClassWithout object and setup with the value of 5 via its constructor, which if there was a few different constructors etc then how would you be sure that the correct constructor was called and thus would the value that you want back from the class really be 5, it could be 0 and another value be that 5!!.