首页 > 技术文章 > $$$ php 常见语法巩固

dh2608 2016-05-16 16:51 原文

strpos() 函数查找字符串在另一字符串中第一次出现的位置

<?php
echo strpos("You love php, I love php too!","php");
?>

运行结果
9

addslashes() 函数 在双引号前添加斜杠

<?php 
$str = addslashes('Shanghai is the "biggest" city in China.');
echo($str); 
?>  

运行实例
Shanghai is the \"biggest\" city in China.

strtolower() 把所有字符转换为小写
<?php
echo strtolower("Hello WORLD.");
?>

运行结果:hello world.
preg_match -- 进行正则表达式匹配

int preg_match ( string pattern, string subject [, array matches [, int flags]] )
preg_match返回pattern所匹配的次数,要么0次(没有匹配)或者1次,因为preg_match()在第一次匹配之后将停止搜素,
preg_match_all()则相反,会一直搜索到subject的结尾处,如果出错preg_match()返回false
提示:  如果只想查看一个字符串是否包含在另一个字符串中,不要用 preg_match()。可以用 strpos()strstr() 替代,要快得多

例子 1. 在文本中搜索“php”

 <?php
// 模式定界符后面的 "i" 表示不区分大小写字母的搜索
if (preg_match ("/php/i", "PHP is the web scripting language of choice.")) {
    print
"A match was found.";
} else {
    print
"A match was not found.";
}
?>

例子 3. 从 URL 中取出域名



<?php
// 从 URL 中取得主机名
preg_match("/^(http:\/\/)?([^\/]+)/i",
    
"http://www.php.net/index.html", $matches);
$host = $matches[2];

// 从主机名中取得后面两段
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo
"domain name is: {$matches[0]}\n";
?>

 

输出结果;domain name is: php.net


例子 2. 搜索单词“web”
<?php
/* 模式中的 \b 表示单词的边界,因此只有独立的 "web" 单词会被匹配,
* 而不会匹配例如 "webbing" 或 "cobweb" 中的一部分 */
if (preg_match ("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
    print
"A match was found.";
} else {
    print
"A match was not found.";
}

if (
preg_match ("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
    print
"A match was found.";
} else {
    print
"A match was not found.";
}
?>

URL Redirect :转发;转发后地址栏将显示目标网址

A站转为B站
URL Frame:隐藏转发;转发后地址栏将显示源网址(A),隐去了B的地址。
URL Redirect :直接转发;转发后地址栏将显示目标网址(B)。



=== 是包括变量值与类型完全相等,而==只是比较两个数的值是否相等。

PHP str_replace() 函数

 

str_replace(find,replace,string,count)

 

参数描述
find 必需。规定要查找的值。
replace 必需。规定替换 find 中的值的值。
string 必需。规定被搜索的字符串。
count 可选。对替换数进行计数的变量。

 


把字符串 "Hello world!" 中的字符 "world" 替换为 "Shanghai"


 stripslashes() 函数

删除反斜杠:

<?php
echo stripslashes("Who\'s Bill Gates?");
?>

运行结果:Who's Bill Gates?

ereg_replace
string ereg_replace ( string $pattern , string $replacement , string $string )

本函数在 string 中扫描与 pattern 匹配的部分,并将其替换为 replacement

 

 

isset

判断变量是否已配置。

语法: int isset(mixed var);

返回值: 整数

函数种类: PHP 系统功能

本函数用来测试变量是否已经配置。若变量已存在则返回 true 值。其它情形返回 false 值。

 

  <?php
$a "test";
echo isset($a); // true
unset($a);
echo isset($a); // false
?>

参考  empty()  unset()

 

 

 trim() 函数   移除字符串

移除字符串两侧的字符("Hello" 中的 "He" 以及 "World" 中的 "d!"):

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
运行结果:Hello World!
llo Worl

如果是 str = trim(str);则是去掉字符串 str 两边的空格

推荐阅读