php擷取字串

2022-04-04 10:12:50 字數 1669 閱讀 9113

1.substr(源字串,其實位置[,長度])-擷取字串返回部分字串

1

<?php

2$str ="phpddt.com";

3echo

substr($str, 2); //

pddt.com

4echo

substr($str, 2,3); //

pdd5

echo

substr($str, -2); //

om 負數從結尾開始取

6 ?>

但是當你擷取中文字串的時候很容易出現亂碼,因為乙個漢字是兩個位元組,而乙個英文本母是乙個位元組。解決辦法如下:

2.mb_substr(),使用方法和substr相同,不過要開啟php.ini裡面extension=php_mbstring.dll擴充套件,不用擔心,一般的空間商

都會開啟這個擴充套件的。

1

<?php

2echo mb_substr("php點點通", 1,3,"utf-8"); //

hp點3 ?>

(1)擷取gb2312中文字串

1

<?php 2//

擷取gb2312中文字串

3function mysubstr($str, $start, $len

) else

11$tmpstr .= substr($str, $i, 1);12}

13return

$tmpstr;14

}15echo mysubstr("php點點通", 1, 5); //

php點

16 ?>

(2)擷取utf8編碼的多位元組字串 

1

<?php 2//

擷取utf8字串

3function utf8substr($str, $from, $len) 4

'. 6 '((?:[\x00-\x7f]|[\xc0-\xff][\x80-\xbf]+)).*#s',

7 '$1',$str

); 8} 9

echo utf8substr("php點點通", 1, 5); //

hp點點通

10 ?>

(3)支援 utf-8、gb2312都支援的漢字擷取函式 

1

<?php 2//

同時支援 utf-8、gb2312都支援的漢字擷取函式 ,預設編碼是utf-8

3function cut_str($string, $sublen, $start = 0, $code = 'utf-8') 4

11else12

24else25

28}

29if(ord(substr($string, $i, 1))>129) $i++;

30}

31if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";

32return

$tmpstr

; 33

} 34}35

$str = "php點點通提供原創php教程";

36echo cut_str($str, 8, 0); //

php點點通提供...

37 ?>

PHP擷取字串

php 自帶幾種字串擷取函式,其中常用到的就是 substr 和 mb substr。前者在處理中文時,gbk 為 2 個長度單位,utf 為 3 個長度單位,後者指定編碼後,乙個中文即為 1 個長度單位。substr 不用說,有時會截 1 3 個中文或半個中文,當然顯示出來是亂碼了,相對來說 mb...

PHP擷取字串

php 構造字串 str abcdefghijklmnopqrstuvwxyz echo 原字串 str.按各種方式進行擷取 str1 substr str,5 echo 從第5個字元開始取至最後 str1.str2 substr str,9,4 echo 從第9個字元開始取4個字元 str2.st...

PHP擷取字串

1.擷取gb2312中文字串 php 擷取中文字串 function mysubstr str,start,len else tmpstr substr str,i,1 return tmpstr 2.擷取utf8編碼的多位元組字串 php 擷取utf8字串 function utf8substr ...