We use the PHP function json_encode(array)
to output JSON
json_encode takes PHP arrays (including nested arrays) and generates JSON strings that can be printed
NOTE: we can also use json_decode to convert json strings into PHP arrays.
<?php
header("Content-Type: application/json");
$output = array();
$output["name"] = "Kyle";
$output["hobbies"] = array("reading", "frisbee");
print(json_encode($output));
?>
Produces:
{
"name":"Kyle",
"hobbies":["reading","frisbee"]
}
Validation: ensuring that form's values are correct
Some types of validation:
Validation can be performed:
Let's validate this form's data on the server...
$city = $_POST["city"];
$state = $_POST["state"];
$zip = $_POST["zip"];
if (!$city || strlen($state) != 2 || strlen($zip) != 5) {
print "Error, invalid city/state/zip submitted.";
}
Basic idea: Examine parameter values, and if they are bad, show an error message and abort. But:
/^[a-zA-Z_\-]+@(([a-zA-Z_\-])+\.)+[a-zA-Z]{2,4}$/
Regular expression ("regex"): a description of a pattern of text
Regular expressions are extremely power but tough to read (the above regular expression matches email addresses)
Regular expressions occur in many places:
split
method (CSE 143
sentence generator)/abc/
In PHP, regexes are strings that begin and end with /
The simplest regexes simply match a particular substring
The above regular expression matches any string containing "abc"
.
A .
matches any character except a \n
line break
A trailing i at the end of a regex (after the closing /) signifies a case-insensitive match
| means OR
() are for grouping
\ starts an escape sequence
* means 0 or more occurrences
+ means 1 or more occurrences
? means 0 or 1 occurrences
{min, max} means between min and max occurrences (inclusive)
min or max may be omitted to specify any number
When you search Google, it shows the number of pages of results as the number of "o"s in the word "Google". What regex matches strings like "Google", "Gooogle", "Goooogle", ...? (try it) (data)
^ represents the beginning of the string or line; $ represents the end
(on the other slides, when we say, /PATTERN/ matches "text", we really mean that it matches any string that contains the text)
[] group characters into a character set; will match any single character from the set
Inside [], many of the modifier keys act as normal characters
What regular expression matches DNA (non-empty strings of A, C, G, and T?)
Inside a character set, specify a range of characters with -
An initial ^ inside a character set negates it
Inside a character set, - must be escaped to be matched
What regular expression matches letter grades such as A, B+, or D-?
What regular expression matches UW Student ID numbers?
What regular expression matches a sequence of only consonants (non-vowel letters) assuming that the string consists only of lowercase letters?
Special escape sequence characters sets
What regular expression matches names in a "Last, First M." format, with any number of spaces?
regex syntax: strings that begin and end with /, such as "/[AEIOU]+/"
function | description |
---|---|
preg_match(regex, string) | returns TRUE if string matches regex |
preg_replace(regex, replacement, string) | returns a new string with all substrings that match regex replaced by replacement |
preg_split(regex, string) | returns an array of strings from given string broken apart using given regex as delimiter (like explode but more powerful) |
$state = $_POST["state"];
if (!preg_match("/^[A-Z]{2}$/", $state)) {
print "Error, invalid state submitted.";
}
preg_match and regexes help you to validate parameters
sites often don't want to give a descriptive error message here (why?)
# replace vowels with stars
$str = "the quick brown fox";
$str = preg_replace("/[aeiou]/", "*", $str);
# "th* q**ck br*wn f*x"
# break apart into words
$words = preg_split("/[ ]+/", $str);
# ("th*", "q**ck", "br*wn", "f*x")
# capitalize words that had 2+ consecutive vowels
for ($i = 0; $i < count($words); $i++) {
if (preg_match("/\\*{2,}/", $words[$i])) {
$words[$i] = strtoupper($words[$i]);
}
} # ("th*", "Q**CK", "br*wn", "f*x")
Create regular expressions like this: let pattern = /cse154/i
Some JavaScript string methods can take Regular Expressions, like search
and replace
.
Additional Regular Expression methods include:
pattern.match("I like CSE154!");
pattern.exec("I like CSE154!");
HTML5 adds a new pattern attribute to input elements
When an input is in a form along with a button, clicking the button automatically verifies the input and does a POST request. To cancel the POST request, add an onsubmit event handler that returns false.