如何将字符串中的汉字移动到字符串的末尾?
How can I move chinese characters in a string to the end of string?
我现在有这样一个字符串:我想在 PHP 中执行以下操作:
$string = 'Testing giving dancing 喝 喝 passing 制图 giving 跑步 吃';
我想把所有的汉字都移到字符串的末尾,并且还要颠倒它们当前的顺序。因此,删除重复的英文单词和 Return 修改后的字符串
给你!查看代码中的注释:
<?php
$string = 'Testing giving dancing 喝 喝 passing 制图 giving 跑步 吃';
// split by a space into an array
$explosion = explode(' ', $string);
$normalWords = [];
$chineseWords = [];
// loop through the array
foreach ($explosion as $debris) {
// if not normal alphabet characters
if (!preg_match('#[a-zA-Z]+#', $debris) && !in_array($debris, $chineseWords)) {
// add to chinese words array if not already in the array
$chineseWords[] = $debris;
} elseif (preg_match('#[a-zA-Z]+#', $debris) && !in_array($debris, $normalWords)) {
// add to normal words array if not already in the array
$normalWords[] = $debris;
}
}
// reverse the chinese characters like you wanted
$chineseWords = array_reverse($chineseWords);
// Piece it all back together
$string = implode(' ', $normalWords) . ' ' . implode(' ', $chineseWords);
// and output
echo $string; // Testing giving dancing passing 吃 跑步 制图 喝
我现在有这样一个字符串:我想在 PHP 中执行以下操作:
$string = 'Testing giving dancing 喝 喝 passing 制图 giving 跑步 吃';
我想把所有的汉字都移到字符串的末尾,并且还要颠倒它们当前的顺序。因此,删除重复的英文单词和 Return 修改后的字符串
给你!查看代码中的注释:
<?php
$string = 'Testing giving dancing 喝 喝 passing 制图 giving 跑步 吃';
// split by a space into an array
$explosion = explode(' ', $string);
$normalWords = [];
$chineseWords = [];
// loop through the array
foreach ($explosion as $debris) {
// if not normal alphabet characters
if (!preg_match('#[a-zA-Z]+#', $debris) && !in_array($debris, $chineseWords)) {
// add to chinese words array if not already in the array
$chineseWords[] = $debris;
} elseif (preg_match('#[a-zA-Z]+#', $debris) && !in_array($debris, $normalWords)) {
// add to normal words array if not already in the array
$normalWords[] = $debris;
}
}
// reverse the chinese characters like you wanted
$chineseWords = array_reverse($chineseWords);
// Piece it all back together
$string = implode(' ', $normalWords) . ' ' . implode(' ', $chineseWords);
// and output
echo $string; // Testing giving dancing passing 吃 跑步 制图 喝