<?php
//1. how to use mail function
//create short variable names
$name=$_POST['name'];
$email=$_POST['email'];
$feedback=$_POST['feedback']; //set up some static information
//$toaddress = "feedback@example.com";
$toaddress = "luoxu@qq.com"; $subject = "Feedback from web site"; $mailcontent = "Customer name: ".filter_var($name)."\n".
"Customer email: ".$email."\n".
"Customer comments:\n".$feedback."\n"; $fromaddress = "From: webserver@example.com"; //invoke mail() function to send mail
mail($toaddress, $subject, $mailcontent, $fromaddress); //2.Trimming Strings chop(), ltrim(), trim()
$str= "inert air ";
echo $str;
$str = trim($str);
chop($str);
echo "<br>"; //3. htmlspecialchars() conflict with html tags $new = htmlspecialchars("<a href='test'>Test</a>");
echo $new; // &lt;a href='test'&gt;Test&lt;/a&gt; $new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href='test'&gt;Test&lt;/a&gt;
echo nl2br("foo isn't\n bar"); //foo isn't<br />bar translate \r\n to <br>
echo nl2br(htmlspecialchars($feedback)); // it will display as newline(line feed)we should use them in this order
echo htmlspecialchars(nl2br($feedback)); //it will display <br> literally
echo '<hr>'; //4.output string
$total =12.345565;
echo "The total amount of order is $total";
printf("The total amount of order is %s ",$total ); //output a formatted string
printf("The total amount of order is %.2f ",$total ); //output a formatted string 12.35
$s =sprintf("The total amount of order is %+s",$total ); // return a formatted string
echo $s;
echo '<hr>'; //5.String case function
$str = "feedback from Website luoxu" ;
echo strtoupper($str);
echo strtolower($str);
echo ucfirst($str); //Feedback from Website luoxu
echo ucwords($str); //Feedback From Website Luoxu
echo "<hr>"; //6.Joining and Spliting Strings with string function
$email = "luoXU@qQ.coM";
$emailArr= explode('@',$email);
print_r($emailArr); //Array ( [0] => luoXU [1] => qQ.coM )
if(strtolower($emailArr[1]) == 'qq.com'){
$toaddress = 'bob@example.com';
}
array_walk($emailArr,"toLowerCase");
function toLowerCase(&$value ){ // needs to add & in front of $value which will affect the $emailArr
$value = strtolower($value);
}
print_r($emailArr); //Array ( [0] => luoxu [1] => qq.com )
$newEmail = implode('@',$emailArr);
echo $newEmail; //luoxu@qq.com //7.strtok()
$str = 'Hello to all of Ukraine'; //split the string with ' ' delimiter as the first substring(token),
// for the second token, you only need to pass the delimiter,
//because strtok() keeps its own internal pointer to its place in the string
echo strtok($str, ' ').' '.strtok(' ').' '.strtok(' '); //Hello to all $string = "This is\tan example\nstring";
/* Use ' ' as tokenizing characters as well */
$tok = strtok($string, " "); while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" ");
}
//Word=This
//Word=is an
//Word=example string /* Use tab and newline as tokenizing characters as well */
$tok = strtok($string, " \n\t"); while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" \n\t");
}
//Word=This
//Word=is
//Word=an
//Word=example
//Word=string
echo "<hr>"; //8.substr()
$test = 'Your customer service is excellent'; //string position starts from 0
echo substr($test,1); //our customer service is excellent
echo substr($test,-9); // excellent
echo substr($test,5,4); //cust
echo substr($test,5,-13); //customer service
echo $test[1]; //o, we can take a string as a array
echo "<hr>"; //9.Comparing Strings
$str1 = "hello";
$str2 = "hello";
$str3 = "aello";
$str4 = "Hello";
echo strcmp($str1,$str2); //0
echo strcmp($str1,$str3).'<br>'; //return a number that is greater than 0 if str1 > str2 alphabetically
echo strcmp($str1,$str4); // H < h in ASCII a number that is greater than 0
echo strcasecmp($str1,$str4).'<br>'; //0
$str5 ='6';
$str6 = '12';
echo strcasecmp($str5,$str6); // result = str6 - str5 ASCII value return 5
echo strnatcmp($str5,$str6); // result = str6 - str5 integer value return -1
echo strlen($str1); //5
echo "<hr>"; //10. Matching and Replacing substring with string function
$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com $user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
echo stristr($email,M); //me@example.com
echo stristr($email,M,true); //na
echo strchr($email,'e'); //e@example.com
echo strpos($email,'m'); //2 starts from 0, the position first occurrence of the needle
echo strrpos($email,'m'); //15 starts from the end , the position first occurrence of the needle reverse
$result = strpos($email,'A'); //not found return false
if($result === false){ //($result == false)is wrong,
// because if we find 'n' in the string , it returns 0, however (0 == false) is true
echo 'not found';
}else{
echo "Found at position:".$result;
}
echo "<hr>"; //11.str_replace();
$bodytag = str_replace("%body%", "black", "|body text='%body%'|");
echo $bodytag; //|body text='black'|
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
echo $onlyconsonants;//Hll Wrld f PHP
//If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject.
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
$newphrase = str_replace($healthy, $yummy, $phrase);
echo $newphrase; //You should eat pizza, beer, and ice cream every day $str = str_replace("ll", "", "good golly miss molly!", $count);
echo $str; //good goy miss moy!
echo $count; //2 2 of 'll' was matched
echo "<hr>"; //replace the substr of string with replacement.take substr_replace('bananas','xyzZ',1,2) as an example
//1. get the substr of the string removing the parts from start to end(length=end-start) substr = b(an)anas, an is removed
//2. insert replacement into substr from start position 1.
echo substr_replace('bananas','xyz',1); //bxyz replace the substr of bananas starting from 1 with xyz
echo substr_replace('bananas','xyzZ',1,2); //bxyzZanas replace the substr of bananas starting from 1 to 3(length is 2) with xyz
echo substr_replace('bananas','xyz',-1); //bananaxyz replace the substr of bananas starting from 1 to 3(length is 2) with xyz
echo substr_replace('bananas','xyz',-1,-2); //bananaxyzs
echo substr_replace('bananas','xyz',4,1); //bbanaxyzas //12.Regular Expression (better to use double quotation mark for strings) less sufficient than string function with similar functionality
//https://regex101.com/ for testing regex
//delimiter: /pattern/ or #pattern#
// using backslash \ to escape / eg: /http:\/\//
//Character Class and Type
//1. /.at/ . means matching a single character, eg:cat,mat,#at,
// /.[a-z]/ when a dot is used at the beginning or end of a Character class, it loses its special wildcardmeaning and becomes just a literal dot
//2. /[a-z]at/ [] means matching a a single character in the square bracket that belongs to a-z ,eg: apple
//3. /[^a-z]at/ ^ (caret) in the square bracket means not to matching any of a single character that belongs to a-z
//4. [[:alnum:]] means alphanumeric character
//4. [[:lower:]] means lower case letters
//5. [[:alpha]1-5] means a class that may contain an alphabetically character or any of the digits from 1-5
//Repetition the three symbols should appear directly after the part of the expression that it applies to
//1. * means 0 or more times
//2. + means 1 or more times
//3. ? means 0 or 1 times
//eg: /[[:alnum:]+]/ means at least one alphanumeric character
//Subexpression using the parenthesis to group certain words (substring) is called inside ()
//eg: /(very )*large/ means 'large', 'very large', 'very very large'
//counted subExpression using curly braces to show repeated times
//eg: /(very){3}/ 3 times exactly
//eg: /(very){1,3}/ very can be repeated 1-3 times, it is 'very' , 'veryvery', 'veryveryvery'
//eg: /(very){2,}/ very can be repeated at least 2 times, it is 'veryvery', 'veryveryvery', and so on
//Anchoring to the beginning or end of a string
//1. ^ caret outside of [] is used at the start of a regular expression to show that it must appear at the beginning of a searched string
//2. $ at the end
//eg: /^bob/ a string starts with bob
//eg: /com$/ a string ends with com
//eg: /^[a-z]$]/ a string contains a single character between a and z
//Branching
// /com|edu|net/ matched one of those three is ok //Matching literal special character
//1. using backslash \ to escape special character
// "\\\\" => '\\' => '\' Matching one '\' needs three \\\ to escape
// "\\\$" => '\$' => '$' Matching one '\' needs three \\\ to escape
//A Summary of Meta Characters used in PCRE regular expression
//1. outside of square bracket : \ ^ $ . | ( ) * + { } ?
//2. inside of square bracket : \ ^ -
//Back Reference
//1. /^([a-z]+) \1 black sheep / "blarge blarge black sheep" matched // functions in PHP for PCRE regular expression
//find substring
preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
//Array ( [0] => Array ( [0] => foobarbaz [1] => 0 )
// [1] => Array ( [0] => foo [1] => 0 )
// [2] => Array ( [0] => bar [1] => 3 )
// [3] => Array ( [0] => baz [1] => 6 ) )
preg_match('/(a)(b)*(c)/', 'ac', $matches);
var_dump($matches);
preg_match('/(a)(b)*(c)/', 'ac', $matches, PREG_UNMATCHED_AS_NULL);
var_dump($matches); //replace substring
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3'; //leave the first group(April),plus a literal 1 and ',' and the third group(2003)
echo preg_replace($pattern, $replacement, $string); //April1,2003 $string = 'The quick brown fox jumps over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string); //The bear black slow jumps over the lazy dog. //splitting strings
$address = 'username@example.com';
$arr = preg_split('/\.|@/', $address);
print_r($arr); //Array ( [0] => username [1] => example [2] => com )

PHP Strings的更多相关文章

  1. Hacker Rank: Two Strings - thinking in C# 15+ ways

    March 18, 2016 Problem statement: https://www.hackerrank.com/challenges/two-strings/submissions/code ...

  2. StackOverFlow排错翻译 - Python字符串替换: How do I replace everything between two strings without replacing the strings?

    StackOverFlow排错翻译 - Python字符串替换: How do I replace everything between two strings without replacing t ...

  3. Multiply Strings

    Given two numbers represented as strings, return multiplication of the numbers as a string. Note: Th ...

  4. [LeetCode] Add Strings 字符串相加

    Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. ...

  5. [LeetCode] Encode and Decode Strings 加码解码字符串

    Design an algorithm to encode a list of strings to a string. The encoded string is then sent over th ...

  6. [LeetCode] Group Shifted Strings 群组偏移字符串

    Given a string, we can "shift" each of its letter to its successive letter, for example: & ...

  7. [LeetCode] Isomorphic Strings 同构字符串

    Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the chara ...

  8. [LeetCode] Multiply Strings 字符串相乘

    Given two numbers represented as strings, return multiplication of the numbers as a string. Note: Th ...

  9. 使用strings查看二进制文件中的字符串

    使用strings查看二进制文件中的字符串 今天介绍的这个小工具叫做strings,它实现功能很简单,就是找出文件内容中的可打印字符串.所谓可打印字符串的涵义是,它的组成部分都是可打印字符,并且以nu ...

  10. LeetCode 205 Isomorphic Strings

    Problem: Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if ...

随机推荐

  1. HDU_4496_逆向并查集

    http://acm.hdu.edu.cn/showproblem.php?pid=4496 逆向并查集,先读取,然后从后向前join每次保存答案即可. #include<iostream> ...

  2. 使用Apache服务器实现Nginx反向代理

    实验环境:centos7 注:因为本次实验在同一台服务器上,Apache与Nginx同为80端口,所以改Apache端口为60 1 配置Nginx服务器: 编辑Nginx配置文件,写入以下内容 loc ...

  3. 用python制作训练集和测试集的图片名列表文本

    # -*- coding: utf-8 -*- from pathlib import Path #从pathlib中导入Path import os import fileinput import ...

  4. 5G为人工智能与工业互联网赋能 高清79页PPT

    人工智能和5G是时下最热门的科技领域之一,两者都是能改变社会,推进下一代工业革命的颠覆性技术. 工业互联网是利用基础科学.工业.信息技术.互联网等领域的综合优势,从大数据应用等软服务切入,注重软件.网 ...

  5. 第三篇 SpringBoot整合log4j2详解

    源代码:https://pan.baidu.com/s/1d1Lwv1gIvVNltIKVWeEseA 提取码:wff0 SpringBoot整合Log4j2步骤: 1.删除spring-boot-s ...

  6. 十天学会CS之操作系统——进程管理01

    进程管理01 进程的概念 进程是计算机中一个非常重要的概念,在整个计算机发展历史中,操作系统中程序运行机制的演变按顺序大致可以分为: 单道程序:通常是指每一次将一个或者一批程序(一个作业)从磁盘加载进 ...

  7. 刷题94. Binary Tree Inorder Traversal

    一.题目说明 题目94. Binary Tree Inorder Traversal,给一个二叉树,返回中序遍历序列.题目难度是Medium! 二.我的解答 用递归遍历,学过数据结构的应该都可以实现. ...

  8. linux中文件处理命令

    目录 touch cat more less head tail touch 解释 命令名称:touch 命令所在路径:/bin/touch 执行权限:所有用户 功能描述:创建空文件 语法 touch ...

  9. [WPF 自定义控件]创建包含CheckBox的ListBoxItem

    1. 前言 Xceed wpftoolkit提供了一个CheckListBox,效果如下: 不过它用起来不怎么样,与其这样还不如参考UWP的ListView实现,而且动画效果也很好看: 它的样式如下: ...

  10. 斯坦福大学cs231n作业参考(中文版)

    cs231n2016冬季课程作业完成,在原先的基础上进行了翻译和中文注释,同时增加了16之后版本的部分新作业文件,已经全部跑通,需要的欢迎自取. 斯坦福大学的 CS231n(全称:面向视觉识别的卷积神 ...