我需要将一个字符串拆分成一个字母数组。问题是,用我的语言(克罗地亚语)也有双字符字母(例如lj,nj,dž)。
因此,应将ljubičicajecvijet
之类的字符串拆分为如下所示的数组:
Array
(
[0] => lj
[1] => u
[2] => b
[3] => i
[4] => č
[5] => i
[6] => c
[7] => a
[8] => j
[9] => e
[10] => c
[11] => v
[12] => i
[13] => j
[14] => e
[15] => t
)
以下是数组中的克罗地亚字符列表(我还包括英文字母)。
$alphabet= array(
'a', 'b', 'c',
'č', 'ć', 'd',
'dž', 'đ', 'e',
'f', 'g', 'h',
'i', 'j', 'k',
'l', 'lj', 'm',
'n', 'nj', 'o',
'p', 'q', 'r',
's', 'š', 't',
'u', 'v', 'w',
'x', 'y', 'z', 'ž'
);
答案 0 :(得分:1)
您可以使用此类解决方案:
数据:强>
$text = 'ljubičicajecviježdžt';
$alphabet = [
'a', 'b', 'c',
'č', 'ć', 'd',
'dž', 'đ', 'e',
'f', 'g', 'h',
'i', 'j', 'k',
'l', 'lj', 'm',
'n', 'nj', 'o',
'p', 'q', 'r',
's', 'š', 't',
'u', 'v', 'w',
'x', 'y', 'z', 'ž'
];
<强> 1。按长度订购结果,以便在开头有双字母
// 2 letters first
usort($alphabet, function($a, $b) {
if( mb_strlen($a) != mb_strlen($b) )
return mb_strlen($a) < mb_strlen($b);
else
return $a > $b;
});
var_dump($alphabet);
<强> 2。最后,拆分。我使用preg_split
函数和preg_quote
来保护函数。
// split
$alphabet = array_map('preg_quote', $alphabet); // protect preg_split
$pattern = implode('|', $alphabet); // 'dž|lj|nj|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|ć|č|đ|š|ž'
var_dump($pattern);
var_dump( preg_split('`(' . $pattern . ')`si', $text, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) );
结果:)
array (size=18)
0 => string 'lj' (length=2)
1 => string 'u' (length=1)
2 => string 'b' (length=1)
3 => string 'i' (length=1)
4 => string 'č' (length=2)
5 => string 'i' (length=1)
6 => string 'c' (length=1)
7 => string 'a' (length=1)
8 => string 'j' (length=1)
9 => string 'e' (length=1)
10 => string 'c' (length=1)
11 => string 'v' (length=1)
12 => string 'i' (length=1)
13 => string 'j' (length=1)
14 => string 'e' (length=1)
15 => string 'ž' (length=2)
16 => string 'dž' (length=3)
17 => string 't' (length=1)
答案 1 :(得分:1)
或者您可以使用它来确保检查每个double是否匹配,如果确实如此(您可以减少$alphabet
- 数组以匹配我的解决方案中的那些双字符:
<?php
ini_set('display_errors',1); // this should be commented out in production environments
error_reporting(E_ALL); // this should be commented out in production environments
$string = 'ljubičicajecvijet';
$alphabet= [
'a', 'b', 'c',
'č', 'ć', 'd',
'dž', 'đ', 'e',
'f', 'g', 'h',
'i', 'j', 'k',
'l', 'lj', 'm',
'n', 'nj', 'o',
'p', 'q', 'r',
's', 'š', 't',
'u', 'v', 'w',
'x', 'y', 'z', 'ž'
];
function str_split_unicode($str, $length = 1) {
$tmp = preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY);
if ($length > 1) {
$chunks = array_chunk($tmp, $length);
foreach ($chunks as $i => $chunk) {
$chunks[$i] = join('', (array) $chunk);
}
$tmp = $chunks;
}
return $tmp;
}
$new_array = str_split_unicode($string,2);
foreach ($new_array as $key => $value) {
if (strlen($value) == 2) {
if (in_array($value, $alphabet)) {
$test[$key] = $value;
unset($new_array[$key]);
}
}
}
$new_array = str_split_unicode(join('',$new_array));
foreach ($test as $key => $value) {
array_splice($new_array, $key, 0, $value);
}
print_r($new_array);
?>