PHP 缩短文本而不用制动词
/*
returns text limited by a specified length of characters but keeping words intact. the final character count will not be exact since it is affected by the possible removing of the a long word or by the addition of the ellipsis.
paramaters:
string - the input string
chars - the length of characters wanted
elli - the ellipsis to be used, defaults to '...'
*/
function shorten($string='', $chars=20, $elli='...'){
list($new_string, $elli)= explode("\n", wordwrap($string, $chars, "\n", false));
return ( $elli ) ? $new_string.'...' : $new_string;
}
PHP 如何使用PHP调整图像大小 - 图像大小调整脚本
<?php
// This is the temporary file created by PHP
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
// Create an Image from it so we can do the resize
$src = imagecreatefromjpeg($uploadedfile);
// Capture the original size of the uploaded image
list($width,$height)=getimagesize($uploadedfile);
// For our purposes, I have resized the image to be
// 600 pixels wide, and maintain the original aspect
// ratio. This prevents the image from being "stretched"
// or "squashed". If you prefer some max width other than
// 600, simply change the $newwidth variable
$newwidth=600;
$newheight=($height/$width)*600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
// this line actually does the image resizing, copying from the original
// image into the $tmp image
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
// now write the resized image to disk. I have assumed that you want the
// resized, uploaded image file to reside in the ./images subdirectory.
$filename = "images/". $_FILES['uploadfile']['name'];
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
// has completed.
?>
PHP 简单的PHP联系表格+ jscript验证+反机器人
CSS
<style type="text/css"> #botty {display:none;} <style>
Javascript
<script type="text/javascript">
function checkform(form){
// check first name
if (form.FirstName.value == "") {
alert( "Please enter your First Name." );
form.FirstName.focus();
return false ;
}
// check last name
if (form.LastName.value == "") {
alert( "Please enter your Last Name." );
form.LastName.focus();
return false ;
}
// check email field
if (form.email.value == "") {
alert( "Please enter your Email Address." );
form.email.focus();
return false ;
}
// check for valid email addy
var apos=form.email.value.indexOf("@");
var dotpos=form.email.value.lastIndexOf(".");
if (apos<1||dotpos-apos<2){
alert("Not A Valid Email Address!");
return false;
}
// ** END **
return true ;
}
</script>
HTML
<form action="contact_handle.php" method="post" name="formy" id="formy">
<p>* Required</p>
<table cellspacing="0" cellpadding="2" border="0" class="webform">
<tbody>
<tr>
<td><label for="Title">Title</label>
<br />
<select name="Title" id="Title" class="cat_dropdown_smaller">
<option value="126631">DR</option>
<option value="126629">MISS</option>
<option value="126627" selected="selected">MR</option>
<option value="126628">MRS</option>
<option value="126630">MS</option>
</select></td>
</tr>
<tr>
<td><label for="FirstName">First Name</label>
<br />
<input name="FirstName" type="text" class="cat_textbox" id="FirstName" size="35" maxlength="255" />
*</td>
</tr>
<tr>
<td><label for="LastName">Last Name</label>
<br />
<input name="LastName" type="text" class="cat_textbox" id="LastName" size="35" maxlength="255" />
*</td>
</tr>
<tr>
<td><label for="email">Email Address</label>
<br />
<input name="email" type="text" class="cat_textbox" id="email" size="35" maxlength="255" />
*</td>
</tr>
<tr>
<td><label for="comments">Comments/Enquiries</label>
<br />
<textarea name="comments" cols="45" rows="8" class="cat_listbox" id="comments" onkeydown="if(this.value.length&gt;=1024)this.value=this.value.substring(0,1023);"></textarea></td>
</tr>
<tr>
<td><input name="subscribe" type="checkbox" id="subscribe" value="yes" />
Subscribe to: Email List Signup</td>
</tr>
<tr>
<td><input type="submit" class="cat_button" value="Submit" id="catwebformbutton" />
<span id="formHide"><input type="text" id="botty" name="botty" /></span>
</td>
</tr>
</tbody>
</table>
</form>
PHP
<?php
//form data
$FirstName = strip_tags($_POST['FirstName']);
$LastName = strip_tags($_POST['LastName']);
$email = strip_tags($_POST['email']);
$subscribe = strip_tags($_POST['subscribe']);
$comments = strip_tags($_POST['comments']);
// prove if a bot has entered data
$botty = strip_tags($_POST['botty']);
if($botty != NULL){
echo "barghh! darn bot!";
die;
}
// the email address where the script will email the form results to
$to = "recipientemail@here.com";
// where the email will look like it is sent from
$from = "info@atsomedomain.com";
$subject = "Email from your website";
$body = "Email from your website" . "
";
$body .= "Name: " . $FirstName . $LastName . "
";
$body .= "Email: " . $email . "
";
$body .= "Newsletter: " . $subscribe . "
";
$body .= "Comments: " . $comments . "
";
$headers = "From: $from" . "
";
$headers .= "Reply-To: $from" . "
";
$headers .= "Return-Path: $from" . "
";
// mail(to,subject,body,headers);
$isMailed = mail($to, $subject, $body, $headers);
if($isMailed){
echo "Thank you for your inquery, " . $FirstName . " " . $LastName . " We will get back to you shortly.";
}else{
echo "There seemed to be a problem";
}
?>
PHP 电话号码beutifier
function format_phone($phone)
{
$prefix = null;
//Check if number has international prefix
switch(true){
case substr($phone, 0, 1) == '+':
$phone = substr($phone, 1);
$prefix = '+';
break;
case substr($phone, 0, 2) == '00':
$phone = substr($phone, 2);
$prefix = '+';
break;
}
//Strip all non numeric characters
$phone = preg_replace("/[^0-9]/", '', $phone);
switch(strlen($phone)){
case 6:
return preg_replace("/([0-9]{2})([0-9]{2})([0-9]{2})/", "$1-$2-$3", $phone);
break;
case 7:
return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
break;
case 10:
return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
break;
case 11:
return preg_replace("/([0-9]{3})([0-9]{4})([0-9]{4})/", $prefix . " ($1) $2-$3", $phone);
break;
case 12:
return preg_replace("/([0-9]{4})([0-9]{4})([0-9]{4})/", $prefix . " ($1) $2-$3", $phone);
break;
default:
return $phone;
break;
}
}
PHP 将任何网站图像保存到您的服务器
<?php
function saveImage($path) {
if ( !preg_match('/\/([^\/]+\.[a-z]{3,4})$/i', $path, $matches) ) die('Use image please');
$image_name = strToLower($matches[1]);
$ch = curl_init ($path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$img = curl_exec ($ch);
curl_close ($ch);
$fp = fopen($image_name,'w');
fwrite($fp, $img);
fclose($fp);
}
saveImage('http://nettuts.s3.cdn.plus.org/513_jsFromNull/javascript-from-null.jpg');
?>
PHP PHP - BBcode
function BBcode($texto){
$a = array(
"/\[i\](.*?)\[\/i\]/is",
"/\[b\](.*?)\[\/b\]/is",
"/\[u\](.*?)\[\/u\]/is",
"/\[img\](.*?)\[\/img\]/is",
"/\[url=(.*?)\](.*?)\[\/url\]/is",
"/\[size=(.*?)\](.*?)\[\/size\]/is",
);
$b = array(
"<i>$1</i>",
"<b>$1</b>",
"<u>$1</u>",
"<img src=\"$1\" />",
"<a href=\"$1\" target=\"_blank\">$2</a>",
'<font size=$1>$2</font>',
);
$texto = preg_replace($a, $b, $texto);
$texto = nl2br($texto);
return $texto;
}
if(isset($_GET['txt'])) {
echo "Has introducido: ".bbcode($_GET['txt']);
}
PHP 格式化手机
function formatPhone($phone = '', $convert = false, $trim = true)
{
// If we have not entered a phone number just return empty
if (empty($phone)) {
return '';
}
// Strip out any extra characters that we do not need only keep letters and numbers
$phone = preg_replace("/[^0-9A-Za-z]/", "", $phone);
// Do we want to convert phone numbers with letters to their number equivalent?
// Samples are: 1-800-TERMINIX, 1-800-FLOWERS, 1-800-Petmeds
if ($convert == true) {
$replace = array('2'=>array('a','b','c'),
'3'=>array('d','e','f'),
'4'=>array('g','h','i'),
'5'=>array('j','k','l'),
'6'=>array('m','n','o'),
'7'=>array('p','q','r','s'),
'8'=>array('t','u','v'), '9'=>array('w','x','y','z'));
// Replace each letter with a number
// Notice this is case insensitive with the str_ireplace instead of str_replace
foreach($replace as $digit=>$letters) {
$phone = str_ireplace($letters, $digit, $phone);
}
}
// If we have a number longer than 11 digits cut the string down to only 11
// This is also only ran if we want to limit only to 11 characters
if ($trim == true && strlen($phone)>11) {
$phone = substr($phone, 0, 11);
}
// Perform phone number formatting here
if (strlen($phone) == 7) {
return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1-$2", $phone);
} elseif (strlen($phone) == 10) {
return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "($1) $2-$3", $phone);
} elseif (strlen($phone) == 11) {
return preg_replace("/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1($2) $3-$4", $phone);
}
// Return original phone if not 7, 10 or 11 digits long
return $phone;
}
PHP php分页
<html>
<head>
<title>Implementing Paging with next and prev</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
include '../library/config.php';
include '../library/opendb.php';
// how many rows to show per page
$rowsPerPage = 20;
// by default we show first page
$pageNum = 1;
// if $_GET['page'] defined, use it as page number
if(isset($_GET['page']))
{
$pageNum = $_GET['page'];
}
// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;
$query = "SELECT val FROM randoms LIMIT $offset, $rowsPerPage";
$result = mysql_query($query) or die('Error, query failed');
// print the random numbers
while(list($val) = mysql_fetch_array($result))
{
echo "$val <br>";
}
echo '<br>';
// how many rows we have in database
$query = "SELECT COUNT(val) AS numrows FROM randoms";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);
$self = $_SERVER['PHP_SELF'];
// creating 'previous' and 'next' link
// plus 'first page' and 'last page' link
// print 'previous' link only if we're not
// on page one
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " <a href=\"$self?page=$page\">[Prev]</a> ";
$first = " <a href=\"$self?page=1\">[First Page]</a> ";
}
else
{
$prev = ' [Prev] '; // we're on page one, don't enable 'previous' link
$first = ' [First Page] '; // nor 'first page' link
}
// print 'next' link only if we're not
// on the last page
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " <a href=\"$self?page=$page\">[Next]</a> ";
$last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> ";
}
else
{
$next = ' [Next] '; // we're on the last page, don't enable 'next' link
$last = ' [Last Page] '; // nor 'last page' link
}
// print the page navigation link
echo $first . $prev . " Showing page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last;
include '../library/closedb.php';
?>
</body>
</html>
PHP 终极验证邮件功能
<?php
function validateEmail($email)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
?>
PHP 下载vCard脚本
<?
/***************************************************************************
PHP vCard class v2.0
(c) Kai Blankenhorn
www.bitfolge.de/en
kaib@bitfolge.de
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
***************************************************************************/
function encode($string) {
return escape(quoted_printable_encode($string));
}
function escape($string) {
return str_replace(";","\;",$string);
}
// taken from PHP documentation comments
function quoted_printable_encode($input, $line_max = 76) {
$hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
$lines = preg_split("/(?:
|\r|\n)/", $input);
$eol = "
";
$linebreak = "=0D=0A";
$escape = "=";
$output = "";
for ($j=0;$j<count($lines);$j++) {
$line = $lines[$j];
$linlen = strlen($line);
$newline = "";
for($i = 0; $i < $linlen; $i++) {
$c = substr($line, $i, 1);
$dec = ord($c);
if ( ($dec == 32) && ($i == ($linlen - 1)) ) { // convert space at eol only
$c = "=20";
} elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
$h2 = floor($dec/16); $h1 = floor($dec%16);
$c = $escape.$hex["$h2"].$hex["$h1"];
}
if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
$output .= $newline.$escape.$eol; // soft line break; " =
" is okay
$newline = " ";
}
$newline .= $c;
} // end of for
$output .= $newline;
if ($j<count($lines)-1) $output .= $linebreak;
}
return trim($output);
}
class vCard {
var $properties;
var $filename;
function setPhoneNumber($number, $type="") {
// type may be PREF | WORK | HOME | VOICE | FAX | MSG | CELL | PAGER | BBS | CAR | MODEM | ISDN | VIDEO or any senseful combination, e.g. "PREF;WORK;VOICE"
$key = "TEL";
if ($type!="") $key .= ";".$type;
$key.= ";ENCODING=QUOTED-PRINTABLE";
$this->properties[$key] = quoted_printable_encode($number);
}
// UNTESTED !!!
function setPhoto($type, $photo) { // $type = "GIF" | "JPEG"
$this->properties["PHOTO;TYPE=$type;ENCODING=BASE64"] = base64_encode($photo);
}
function setFormattedName($name) {
$this->properties["FN"] = quoted_printable_encode($name);
}
function setName($family="", $first="", $additional="", $prefix="", $suffix="") {
$this->properties["N"] = "$family;$first;$additional;$prefix;$suffix";
$this->filename = "$first%20$family.vcf";
if ($this->properties["FN"]=="") $this->setFormattedName(trim("$prefix $first $additional $family $suffix"));
}
function setBirthday($date) { // $date format is YYYY-MM-DD
$this->properties["BDAY"] = $date;
}
function setAddress($postoffice="", $extended="", $street="", $city="", $region="", $zip="", $country="", $type="HOME;POSTAL") {
// $type may be DOM | INTL | POSTAL | PARCEL | HOME | WORK or any combination of these: e.g. "WORK;PARCEL;POSTAL"
$key = "ADR";
if ($type!="") $key.= ";$type";
$key.= ";ENCODING=QUOTED-PRINTABLE";
$this->properties[$key] = encode($name).";".encode($extended).";".encode($street).";".encode($city).";".encode($region).";".encode($zip).";".encode($country);
if ($this->properties["LABEL;$type;ENCODING=QUOTED-PRINTABLE"] == "") {
//$this->setLabel($postoffice, $extended, $street, $city, $region, $zip, $country, $type);
}
}
function setLabel($postoffice="", $extended="", $street="", $city="", $region="", $zip="", $country="", $type="HOME;POSTAL") {
$label = "";
if ($postoffice!="") $label.= "$postoffice
";
if ($extended!="") $label.= "$extended
";
if ($street!="") $label.= "$street
";
if ($zip!="") $label.= "$zip ";
if ($city!="") $label.= "$city
";
if ($region!="") $label.= "$region
";
if ($country!="") $country.= "$country
";
$this->properties["LABEL;$type;ENCODING=QUOTED-PRINTABLE"] = quoted_printable_encode($label);
}
function setEmail($address) {
$this->properties["EMAIL;INTERNET"] = $address;
}
function setNote($note) {
$this->properties["NOTE;ENCODING=QUOTED-PRINTABLE"] = quoted_printable_encode($note);
}
function setURL($url, $type="") {
// $type may be WORK | HOME
$key = "URL";
if ($type!="") $key.= ";$type";
$this->properties[$key] = $url;
}
function getVCard() {
$text = "BEGIN:VCARD
";
$text.= "VERSION:2.1
";
foreach($this->properties as $key => $value) {
$text.= "$key:$value
";
}
$text.= "REV:".date("Y-m-d")."T".date("H:i:s")."Z
";
$text.= "MAILER:PHP vCard class by Kai Blankenhorn
";
$text.= "END:VCARD
";
return $text;
}
function getFileName() {
return $this->filename;
}
}
// USAGE EXAMPLE
$v = new vCard();
$v->setPhoneNumber("+49 23 456789", "PREF;HOME;VOICE");
$v->setName("Mustermann", "Thomas", "", "Herr");
$v->setBirthday("1960-07-31");
$v->setAddress("", "", "Musterstrasse 20", "Musterstadt", "", "98765", "Deutschland");
$v->setEmail("thomas.mustermann@thomas-mustermann.de");
$v->setNote("You can take some notes here.
Multiple lines are supported via \\r\\n.");
$v->setURL("http://www.thomas-mustermann.de", "WORK");
$output = $v->getVCard();
$filename = $v->getFileName();
Header("Content-Disposition: attachment; filename=$filename");
Header("Content-Length: ".strlen($output));
Header("Connection: close");
Header("Content-Type: text/x-vCard; name=$filename");
echo $output;
?>