Page 1 of 1

String Character Validator return true or false based on the characters inside a string. Rate Topic: -----

#1 engale  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 3
  • View blog
  • Posts: 594
  • Joined: 30-September 08

Posted 05 October 2008 - 01:31 PM

This code is designed to take a string and validate it's characters, I'll take you through step by step to show you what happens.

First we need to define a function we are going to call our function "str_is_valid()" when we call this function we need to send to it the string we are going to be validating the characters of, so to do that we add what we want to call this variable in the () part of the function decleration. Our Variable will be called $strtoval. The end product of setting up this function will be:
function str_is_valid($strtoval) {

}



Good, now we have a function that we can call later and send the function a variable string so now what?

Well now we tell the function what it is going to do. You will probaly note there is a funny looking bracket in the code box that looks like "{". This bracket is a container, it will contain the code of the function and is closed, taped up, how ever you want to think about it by the opposed bracket at the end of the function that looks like "}". Now everything inside these brackets will happen when you call the function.

So what are we going to do inside of these brackets? Well, honestly you can do what ever you want to have your code do, if you can code it but for the reasons of this tutorial we are going to have code that will determine if a string is using valid characters or not.

First we need to do some set up, we have a string, and though there are some better ways to do this, I'm going to use some extra commands so that I can walk you though them, the end result will be the same.

The first thing we are going to do is locate the lenth of the string sent to the function. We are going to use the "strlen()" code to do this.
This code is simple, we supply the string we want to know the lenth of and it returns the lenth in a decimal number (base of 10). we do this by simply supplying the string in the () of the function, now just putting the code "strlen($strtoval)" will only give the lenth of the variable, if we plan to use this value we need to create a new variable to hold this number. The statement below will do that nicely for us.
  $num = strlen($strtoval);



Now the function has a variable we can call on anytime inside the function, after the function is closed though this variable is destroyed, and is of no more use to us. That is ok, we only need this variable inside of this function.

Now the next thing we are going to need is to seperate the string's characters, now there are a few ways to do this but I want to teach you the "chunk_split()" function of PHP. This function is designed to insert a certian string inbetween characters in a string. Now, lets give a slight example so you understand what that means if I'm unclear.

Example of "chunk_split()":
<?php
$str = "Hello world!";
echo chunk_split($str,1,".");
?> 


The output of the code above will be:
H.e.l.l.o. .w.o.r.l.d.!.
(This example barrowed from w3schools).

Now a little bit more information on this function:
This function requires only one input, that of the string, but accepts two other inputs. they are that of the lenth you want the chunks in and it's default "76". The second is a string that defines what to place at the end of each chunk. Default for this is "\r\n".

Now for our code we are going to insert the string "(*)" inbetween each character in the string. We need then to tell the function what string we want to chunk by the string (*), and also how many characters to skip before the next (*) is placed into the string.

Just like with the strlen() function we are going to need to set this to a variable so that the code actualy saves it.
So we know we want the code to chunk_split($strtoval), we want it to do this every one character and that we want it to insert (*).
Because we know the default number of skipped characers is 76 we know we need to change that, but how?
Well we simply tell it to inside the function IE:chunk_split($strtoval,1).
Now we also want to change the defaulted "\r\n" to the "(*)" for our code, well this is achieved again by telling it to change the default inside the function IE:chunk_split($strtoval,1,"(*)"). So we are going to set our function to a variable, in this case "$cs_str".

  $cs_str = chunk_split($strtoval,1,"(*)");



Now, just so you are aware we did the above and we now have a new variable that we defined inside a function. Just like the variable before and every other variable defined inside a function, this variable is only good inside this function. Now, on that note, if variables diefined inside a function are only good inside of that function, why would we bother to use functions? The return feature, witch will be shown later will answer your questions so lets keep going for now and come back to this.

Ok now we have the lenth of a string sent to the function and that string with "(*)" splitting up each character of that string, now what?
Time for another PHP function, and if you like explosions you'll be a litte bit disapointed but it is the "explode()" function. This function will return an array.

First off, what is an array? An array is a variable set, this set is separated inside the same variable. We can access a different part of the set by knowing it's ID. Now again referencing from W3schools, There are three different kind of arrays:
  • Numeric array - An array with a numeric ID key
  • Associative array - An array where each ID key is associated with a value
  • Multidimensional array - An array containing one or more arrays

If you feel it would be worth it to you to find out more about arrays you can reference w3schools - array.

Back to the explode() function, what, besides creating array, will it do? Well it in essence explodes the string, at premarked places into smaller segments, each segment is, in the left to right order, returned to the next numeric ID starting with 0. Our premarker will be the "(*)" we set into the $cs_str variable. So to explode we do this...

  $ex_str = explode("(*)",$cs_str);



Now, if you want to set an array, witch we need to do in our code, we are going to use another function of PHP called "array()". Real they couldn't have hidden this function in plain sight better could they? Well, we now understand we can set an array with this function but how? Well this function will again return an array with numeric IDs starting with 0. The set up is simple, in the order you want your array set up, simply supply the values IE: array("0","1") They really try to make this hard don't they?

Now like every other function we need to set it to a variable if we plan on useing the result, the lucky thing about the array() function. So for us and this tutorial why do we want another array? Well this is where we will set our valid characters to test against the string characters. For our example our array will have 36 IDs (0-35) because we want the valid characters to be letters and numbers (a-z and 0-9).

  $valid = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9");



Now to teach a nother feature of PHP, the while loop. The while loop is very simple in design, while this do that. We need then a while that will run for the lenth of the string($num). So we are going to need another variable, we will call this "$i" and set it to 0. We will then tell our while loop to run while $i is less than the lenth of our sting($num). Inside the while loop we are going to increase the value of $i by one so that eventualy $i will be = to the value of $num and end our while loop and continue with the rest of our function. Like C++ we can use the ++ operator to mean "$i = $i + 1".

  $i=0;
  while( $i < $num ) {
  
  $i++;
  }



Now this while loop is doing nothing but "$i++". So we need to run our check still inside our while. We are going to need another while to do this still, this while loop will be the for the number of ID in the array "$vallid". For this we will need to find out what that number is. There is already a PHP feature that will count these IDs for us and it's called shockingly "count()". the count() function simply takes an array variable and counts the ids then returns the value. The other thing we need for this while loop will be the current ID we are texting the value of. We will assing this variable the name of "$x". We put this while loop inside of the other while loop, because of this, this while loop will do a full run for each run the first while will do.

		  $x = 0;
	while ( $x < count($valid) ) {

	  $x++;
	}



Ok so far:
  • Our string's characters one by one are inside an array called "$ex_str".
  • The first while loop is setup to run from 0 to the lenth of the string we are testing is valid.
  • The second while loop is inside of the first so we can run a check of the current character against all of the valid characters.

Now we need to run this check. For this we are going to use the "if then" statment. The way the if then statment works is really just like it sounds if this, then do that. Really how much simpler can that be?

For our check if our current character ("$i") equals the current valid test character ("$x"), then we will set an array variable "$test" to one in the spot of the current character("$i"). So we need to learn how to set up the if then statement. first we declare the if then we tell it what to test inside of (), in our case, if ( $ex_str[$i] = $valid[$x] ) is our test. Now so you know this is not the correct decleration of the if, while that looks right, in programming the "=" symbol means "is" thus "$i = 0" means "$i is 0". So with the code we just put in the if we actualy made $ex_str[$i] the value of $valid[$x]. That is not want we want to do. We want to find out if it is equal, that symbol is "==" that's it. so we will refine our statment to ask porperly, "if ( $ex_str[$i] == $valid[$x] )".

	  if ( $ex_str[$i] == $valid[$x] ) {

	  }


Here we are using the boxing characters "{}" to contain the THEN statment. In this case "$test[$i] = 1" will be our Then Statement. Up until this point we have only been setting arrays with the PHP functions but you can set an array but calling the array variable and it's id and telling the code what it is equal to.

			   $test[$i] = 1



Now our second while loop, the one that actualy finds out if the character is in the valid array, is finished. Now we need to do another test.
This test will be to find out if the character was not found in the valid array. We will use another if then statment to do this, and since we set a variable ($test[$i]) to 1 if the value was found in the valid array we can test with that. So what we want to find out in simple terms is if $test[$i] does not equal 1. There luckly is a "not" symbol and that is the "!" symbol. Now this in combination with "=" means "not equal to" thus "!=" will be our test.

	if ( $test[$i] != 1 ) {

	}



Now we have our test in place. So now, if the test passes we don't need our function to go any further, we know that the value of the character did not match any of the values in our valid array. So, because of this, the string does not contain only valid charcters so let us end this now.

We will be able to end the function with the "return" command. This statement will return, back to the line of code that called the function with the value supplyed to the return. In this case we only need to know if the string is valid or not IE: true or false, but you can return the value of a variable, array, or a string in quotes (""). Since we know inside of this then statment is happening after we find the character did not match a character in the valid array we will then return a false statement to the code calling our function.

	  return false;



Yet on the other hand if the code makes it to the end of the function, then the function never returned false. This only means that all the characters in the string matched one of the characters in our valid array, or that our sting is only composed of valid character, wait that's what we wanted to know, so we can return true before we end the function.

  return true;
}



With that finished now you can call this function with the line "str_is_val()". Now with that you need to tell our function what string you are trying to validate, and for this function, it is most likely user input (a string returned from a form). So we can jump the chase a bit by calling the function this way:

str_is_val($_POST['fldname']);



With that line not much is going to happen but if you use this inside a if then statement you can do much more....

if ( str_is_val($_POST['fldname']) ) {
  echo "This string is useing only valid characters.";
}




Just to be nice the code in compleation is:

function str_is_val($strtoval) {
  $num = strlen($strtoval);
  $cs_str = chunk_split($strtoval,1,"(*)");
  $ex_str = explode("(*)",$cs_str);
  $i=0;
  $valid = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9");
  while( $i < $num ) {
	$x = 0;
	while ( $x < count($valid) ) {
	  if ( $ex_str[$i] == $valid[$x] ) {
		$test[$i] = 1;
	  }
	  $x++;
	}
	if ( $test[$i] != 1 ) {
	  return false;
	}
	$i++;
  }
  return true;
}



Is This A Good Question/Topic? 0
  • +

Page 1 of 1