Chen Log

陳洛格

PHP 爆炸字元與爆炸字串變陣列的方法

leave a comment »

爆炸字串很簡單

// Example 1
$pizza = “piece1 piece2 piece3 piece4 piece5 piece6”;
$pieces = explode(” “, $pizza);

只要有空格的狀態下,這樣就分開了。

可參考 http://php.net/manual/en/function.explode.php

 

但是爆炸字元有點麻煩:

$str = “Hello Friend”;
$arr1 = str_split($str);

會變成

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

可參考 http://www.php.net/manual/en/function.str-split.php

因為中文utf8是3個字元,

所以爆炸字元會失敗,

解決方法:

function mb_str_split( $string ) { 
# Split at all position not after the start: ^ 
# and not before the end: $ 
return preg_split(‘/(?<!^)(?!$)/u’, $string ); 

$string = ‘火车票’
$charlist = mb_str_split( $string ); 

print_r( $charlist ); 
?> 

# Prints:
Array
(
[0] => 火
[1] => 车
[2] => 票
)

 

Advertisements

Written by chenagw

2012/04/09 at 01:21

Posted in Uncategorized

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: