Parse PHP Message function Description of the main function of this module (code can be implemented) _php tips

Source: Internet
Author: User
Tags numeric mixed readable
One, sensitive word processing
1, filter sensitive words
The Preg_match () function is used to search for all content that matches a given regular expression in a string, and returns True if it exists, or false.

Grammar:
int Preg_match (string pattern,string subject[,array Matches[,int flags]])
The Preg_match () function parameter is described as follows:
Pattern:
necessary parameters, matching regular expressions are required
Subject:The necessary parameters, the input string
matches:Optional parameters. An array of output search results, such as $out[0], will contain results that match the entire pattern, $out [1] will contain the results that match the child patterns in the first captured parentheses, and so on.
Flags:Optional parameters. Tags: preg_offset_capture, which returns an attached string offset for each occurrence of the resulting page, PHP4.3.0 available.

The implementation methods are as follows:
First, the file () function is used to read the sensitive words in the stored child text file (each sensitive word is a separate line) and is stored in the array $file_word.
Then, using the FOR loop statement to automatically read the array elements (sensitive words), directly through the regular expression to verify that the user submitted messages contain sensitive words.

When the user post message, submit Liyan information, the message and stored in the array of sensitive words to compare, if the message contains sensitive words, then pop-up prompts, otherwise message information published successfully. The key code for implementing sensitive word filtering is as follows:
Copy Code code as follows:

if (Is_file ("./filterwords.txt")) {//Determine if the given file name is a normal file
$filter _word = File ("Filterwords.txt"); Read the entire file into an array
$str =$_post[' content '];
for ($i =0; $i <count ($filter _word); $i + +) {//apply a For loop statement to judge sensitive words
if (Preg_match ("/") Trim ($filter _word[$i]). " /i ", $str)) {//Apply regular expressions to determine whether or not a sensitive word is included in the message being passed
echo "<script> alert (' message contains sensitive words! '); History.back ( -1);</script> ";
Exit
}
}
}

file () function
Array file (string filename [, int use_include_path [, resource context]])
As with ReadFile (), only file () is returned as an array. Each cell in the array is the corresponding line in the file, including line breaks. If failure file () returns FALSE.
2, add sensitive words to text file
PHP writes the main function of a sensitive Word application to a text file
(1) is_writable () function
The is_writable () function is used to determine whether a file exists and is writable, and returns true if the above conditions are met, or false.
Syntax: bool is_writable (string filename) parameter filename is used to specify the full path of the file(c:/leavemessage/filterwords.txt) or relative path (relative to call file path Filterwords.txt), writable returns TRUE, not writable returns false
Example:
Copy Code code as follows:

if (is_writable ("Filterwords.txt")) {
echo "Writable file";
} else {
echo "Cannot write file";
}

(2) fopen () function
The fopen () function is used to open a file and return the indicator pointer for that file. The file can be local or remote.
Syntax: Resource fopen (String filename,string mode[,int Use_include_path[,resource context])
Parameters:
FileName:
Necessary parameters. Used to specify a local or remote address to open a file
mode:Necessary parameters. Used to specify the mode Use_include_path to open the file: Optional parameters. If you set this parameter to true,php, you will try to open the file according to each point in the Include_path standard include path
Context: Optional parameter. Set some options for improving file flow performance

Mode file Open Pattern parameter description:
The ' R ' read-only mode opens, pointing the file pointer to the file header.
' r+ ' read-write mode opens, pointing the file pointer to the file header.
The ' W ' write mode opens, pointing the file pointer to the file header and truncating the file size to zero. If the file does not exist, try creating it.
' w+ ' read-write mode opens, points the file pointer to the file header and truncates the file size to zero. If the file does not exist, try creating it.
The ' a ' write mode opens, pointing the file pointer at the end of the file. If the file does not exist, try creating it.
An ' A + ' read-write mode opens, pointing the file pointer to the end of the file. If the file does not exist, try creating it. ' X ' is created and opened in writing, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns FALSE, and a e_warning level error message is generated. If the file does not exist, try creating it. This and specifies the o_excl| for the underlying open (2) system call The o_creat tag is equivalent. This option is supported by PHP4.3.2 and later versions and can only be used for local files. ' x+ ' is created and opened in read-write mode, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns FALSE, and a e_warning level error message is generated. If the file does not exist, try creating it. This and specifies the o_excl| for the underlying open (2) system call The o_creat tag is equivalent. This option is supported by PHP 4.3.2 and later versions and can only be used for local files.

Example: the fopen () function opens a file as read-only
Copy Code code as follows:

<?php
$FP =fopen ("Filterwords.txt", "R");
?>

(3) fseek () function
Fseek () function to set the location of the file pointer
syntax: int fseek (Resource handle,int offset[,int whence])
Parameters:
Handle:
Necessary parameters. The identity of the file returned after opening a file
Offset:Necessary parameters. Where to set the file pointer
whence:can be provincial parameters.
Fessk ()Description of the whence parameter of the function
Seek_set:The set position equals offset bytes. The value is the default value for this parameter
seek_cur:Set position equals current position plus offset bytes
Seek_end:Set position equals file end plus offset bytes
For example, apply the fopen () function to open the file "Test.txt" and then read the 4,096-byte contents of the file, and then apply the fseek () function to restore the file pointer to its original location.
Copy Code code as follows:

<?php
$FP =fopen ("Filterwords.txt", "R"); Open a file as read-only
$data =fgets ($fp, 4096); Read 4,096 bytes of content in a file
Fseek ($fp, 0); Position the file pointer to the NO. 0 byte
?>

String fgets (int handle[,int length])
Reads a row from the file pointed to by handle and returns a string with a maximum length of length-1 bytes. Stops when a line break is encountered (including in the return value), EOF, or after the length-1 byte has been read (see what happens first). If length is not specified, the default is 1 K, or 1024 bytes. (In view of the program execution efficiency, the general still chooses a fixed length value)
(4) fwrite () function
The fwrite () function is used to write a string to the specified file and to specify the size of the write byte.
syntax: int fwrite (Resource handle,string string[,int length])
parameter Description:
Handle:
Necessary parameters. File identification pointer
string:Necessary parameters. The string to write to a file
Length:can be provincial parameters. Refers to the length of the file being written and, if omitted, writes all the contents of the specified string to the file
For example: the fwrite () function writes the string "PHP message book" to the Filterwords.txt file
Copy Code code as follows:

<?php
$FP =fopen ("Filterwords.txt", "w+");
$STR = "php message book";
if (fwrite ($FP, $str)) {
echo "File Write success!" ";
}else{
echo "File write Failed";
}
?>

(5) fclose () function
The fclose () function closes the file that the specified file identity refers to.
Syntax: BOOL fclose (resource handle)
Parameter handle is the identity of the file returned after a file was successfully opened by the fopen () function or the Fsockopen () function.
In this module, add the function of the sensitive word to the text file "Filterwords.txt" by the function described above.
Copy Code code as follows:

<?php
if ($_post) {
$filename = ". /filterwords.txt ";
if (is_writable ($filename)) {
$file =fopen ($filename, ' r+ '); Read-write mode opens, pointing the file pointer to the file header.
}
else{
echo "File". $filename. " Not writable ";
}
Writing files at the end of a file
Fseek ($file, 0,seek_end); Sets the position of the pointer, seek_end setting is equal to the end of the file plus offset (here is 0) bytes
$word =$_post[txt_word];
Fwrite ($file, $word);
Fwrite ($file, "\ r \ n");
Fclose ($file);
}
?>

3, read the sensitive words in the file
Copy Code code as follows:

<?php
$filename = ". /filterwords.txt ";
if (is_readable ($filename)) {
$arr =file ($filename);
}
else{
echo "File". $filename. " Not readable ";
}
while (list ($name, $value) =each ($arr)) {//traversal array
$a. = "$value". ",";
}
echo "<br> sensitive words are as follows:<br>". $a;
?>

(1) is_readable () determines whether the file exists and is readable and returns true if the above conditions are met
Syntax: bool is_readable (string filename),Parameter filename is used to specify the full path of the file
(2) void list (mixed ...)
Like Array (), this is not a real function, but a language structure. List () assigns a set of variables in one step. The list () can only be used for arrays of numeric indices and assumes that the numeric index starts at 0.
For example:
Copy Code code as follows:

<?php
$info = Array (' coffee ', ' brown ', ' caffeine ');
List ($drink, $color, $power) = $info;
Print "$drink is $color and $power makes it special.\n";
Coffee is brown and caffeine makes it special.
List ($drink, $color) = $info;
Print "$drink is $color. \ n";
Coffee is brown.
?>

(3) array each (array array)
Returns the key and value of the current position of the pointer in array arrays and moves the array pointer forward. A key-value pair is returned as an array of four cells, with the key named 0,1,key and value. Unit 0 and key contain the key names of the array cells, and 1 and value contain data. Each () returns false if the internal pointer crosses the end of the array.
Copy Code code as follows:

<?php
$foo = Array ("Bob", "Fred", "Jussi", "Jouni", "Egon", "Marliese");
$bar = each ($foo);
Print_r ($bar);
?>

Each () returns the following array
Array
{
[1] => Bob
[Value] => bob
[0] => 0
[Key] => 0
}
The list () only works on the numeric index, and the default key starts at zero. So list ($name, $value) assigns key 0 and value Bob to $name and $value respectively.
4, the implementation of the check box selection and counter-election
Depending on the content in the database, the number of dynamically created check boxes for the FOR Loop statement is applied, and the check box that is selected or reversed must set name to note_id[], and the value of the checkbox is the ID number of the message.

<input type= "checkbox" Name= "note_id[" value= echo $id;? > "/>
Add a fully selected checkbox as the content you want to select. When the check box is checked, the Custom function Check_all () function is invoked to set the full selection of the check box.

<input type= "checkbox" Name= "Select_all" onclick= "Check_all (this.form)"/>
<span class= "Style1" > Full selection </span>
The fully selected implementation, traversing all the checkbox form.elements[i], and setting the checked property of each multiple option to true.
An form.elements[i implementation that traverses all check boxes, gets the Checked property value of the check box, and if true, sets to false, otherwise set to true, which is the opposite setting for the current value.
Copy Code code as follows:

<script language= "JavaScript" >
checkbox in anti-select form
function inverse (form) {
for (Var i=0;i<form.elements.length-2;i++) {
Form.elements.length get the number of page form input elements, such as checkbox,radio,text,button,submit, etc.
var e = form.elements[i];
E.checked = = true? e.checked = false:e.checked = true;
}
}
Select all Check_box in the form
function Check_all (form) {
for (Var i=0;i<form.elements.length-2;i++) {
var e=form.elements[i];
E.checked=true;
}
}
</script>

Two, message this code analysis
1,SUBSTR () intercepting Chinese string problems
function: String substr (string string, int start, int [length]);
parameter Description:
String:
Must, represents the string to be processed
Start:Must be taken from the start bit of the string string and, if start is a negative number, from the end of the string
Length:Optional, indicating the length of the string to take, if length is a negative number, then the penultimate length character is taken
Chinese characters take up two lengths, and English characters and symbols take up a length. The PHP built-in function substr (string str,intstart,[int length]) is used to intercept the specified string length. There is no problem in intercepting English strings, but in the case of intercepting Chinese or mixed strings, the last character becomes a question mark.
The following is a custom Chinese string intercept function:
Copy Code code as follows:

function Str_cut ($str, $start, $length) {//Chinese string intercept functions
$str _new=iconv_substr ($str, $start, $length, "utf-8");
if ($start ==0) {
if (strlen (Utf8_decode ($STR)) > ($length + $start)) {
$str _new.= ".";
}
}
return $STR _new;
}

The 2,htmlspecialchars () function converts some predefined characters to HTML entities. The function is to prevent the user from illegal operation.
For example:
Copy Code code as follows:

$str = ' <div> I added half a layer </div></td> half table row tag <br/><a href= "<a href=" http://www.jb51.net/" >http://www.jb51.net</a> "> Cloud-dwelling community </a>";
echo Htmlspecialchars ($STR);

The output is:
<div> I added half layer </div></td> half table row tag <br/><a href= "<a href=" http://www.jb51.net/">http" ://www.jb51.net</a> "> Cloud Habitat Community </a>
the 3,str_replace () function replaces some other characters in a string with a string.
Syntax: Str_replace (Find,replace,string,count)
parameter Description:
Find:
Have to. Specify the value to find.
Replace:Have to. Specify the value to replace the Find content
string:Have to. Specify the string to be searched for
Count:Optional. A variable that counts the number of replacements
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.