woff 發表於 2010-4-12 12:16:09

PHP substr 分割文字 utf-8

語法 : string substr (字串, 起始點 [, 擷取長度])

其中字串的起始點由0開始,可以為正數或負數,
例如:
字串 "abcdef", 0就是代表從 a 開始 ,-2代表從 e 開始

擷取長度 則為起始點後的幾個字
<?php
$rest = substr("abcdef", -1);    // returns "f"

$rest = substr("abcdef", -2);    // returns "ef"

$rest = substr("abcdef", -3, 1); // returns "d"

?>
英文數字切割只要用substr就綽綽有餘,那若有包含中文字呢???
以目前大部分網頁都是utf8為例,中文字為3個位元組,若混合英數符號,
只有一個位元組的字,勢必在分隔文字會出現錯亂...


psir這邊不私藏,分享兩個好用的函式提供有興趣的同好來使用,
加入會員回覆後即可觀看

1. function utf8Slices($string,$length=0,$start=0,$slices=false,$dotted_line=false )
$slices : true 返回字串false返回字數
$dotted_line : true 過長自動加...false過長不自動加....

2. function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')

以上都為分割中文字的補強函式,請慢用

**** Hidden Message *****

ckchan1307 發表於 2010-5-12 13:47:35

good sample 20 20 20 20!!
good sample 20 20 20 20

mixcat329 發表於 2010-9-10 20:24:46

想知道~~感激不盡耶!!

purindog 發表於 2011-2-21 12:05:26

謝謝你無私的分享~~謝謝

bknet 發表於 2011-12-29 20:52:26

感謝大大的分享
頁: [1]
查看完整版本: PHP substr 分割文字 utf-8