Heim  >  Artikel  >  Backend-Entwicklung  >  php中有关字符串的4个函数substr、strrchr、strstr、ereg介绍和使用例子_PHP教程

php中有关字符串的4个函数substr、strrchr、strstr、ereg介绍和使用例子_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:31:56802Durchsuche

一、取部份字符串。

复制代码 代码如下:
string substr(string string, int start, int [length]);

本函数将字符串 string 的第 start 位起的字符串取出 length 个字符。若 start 为负数,

则从字符串尾端算起。若可省略的参数 length 存在,但为负数,则表示取到倒数第 length 个字符。

复制代码 代码如下:

echo  substr ( "abcdef" ,  1 ,  3 );   // 返回 "bcd"
echo  substr ( "abcdef" , - 2 );     // 返回 "ef"
echo  substr ( "abcdef" , - 3 ,  1 );  // 返回 "d"
echo  substr ( "abcdef" ,  1 , - 1 );  // 返回 "bcde"

二、取得某字符最后出现处起的字符串。

复制代码 代码如下:
string strrchr(string haystack, string needle);

本函数用来寻找字符串 haystack 中的字符 needle 最后出现位置,并将此位置起至字符串

haystack 结束之间的字符串返回。若没有找到 needle 则返回 false。

复制代码 代码如下:

$PATH="http://localhost/test/test.php";
$dir = substr( strrchr( $PATH, ":" ), 1 );
echo $dir;

输出://localhost/test/test.php


三、返回字符串中某字符串开始处至结束的字符串。

复制代码 代码如下:
string strstr(string haystack, string needle);

本函数将 needle 最先出现在 haystack 处起至 haystack 结束的字符串返回。若找不到 needle 则返回 false。
 

四、字符串比对解析。

复制代码 代码如下:
int ereg(string pattern, string string, array [regs]);

本函数以 pattern 的规则来解析比对字符串 string。比对结果返回的值放在数组参数 regs 之中,regs[0] 内容就是原字符串 string、regs[1] 为第一个合乎规则的字符串、regs[2] 就是第二个合乎规则的字符串,余类推。若省略参数 regs,则只是单纯地比对,找到则返回值为 true。

复制代码 代码如下:

if ( eregi ( "^ [ _/.0-9a-z- ] +@( [ 0-9a-z ][ 0-9a-z- ] +/.)+ [ a-z ]{ 2,3 }$ " , $email )) {
  echo  "您的 E-Mail 通过初步检查" ;
}

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/760293.htmlTechArticle一、取部份字符串。 复制代码 代码如下: string substr(string string, int start, int [length]); 本函数将字符串 string 的第 start 位起的字符串取出 len...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn