php - 如何将字符串中的中文字符移动到字符串的末尾?
问题描述
我现在有一个这样的字符串:我想在 PHP 中执行以下操作:
$string = 'Testing giving dancing 喝 喝 passing 制图 giving 跑步 吃';
我想将所有中文字符移到字符串的末尾,并且还要颠倒它们当前的顺序。因此,删除重复的英文单词并返回修改后的字符串
解决方案
干得好!检查代码中的注释:
<?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 吃 跑步 制图 喝
推荐阅读
- javascript - XMLHttpRequest 服务器响应状态为 405(不允许方法)
- javascript - react-table 'pivotBy' :如何在 pivotBy 中使用的列上进行过滤
- gradle - 模块不在 Gradle 视图中
- git - git - 推送时在仓库中保留特定文件
- android - 如何从 Android App Incoming Intent 获取 URI
- c - 在哪里可以找到 Apache 用于处理 .htaccess 的源代码?
- python-3.x - 从单词列表中查找给定句子的字谜
- apache - 子文件夹 .htacess 不覆盖父 .htacess 选项
- java - 获得(有效的)电子贸易API访问令牌后如何解决401?
- assembly - 如何使用 GNU as/GNU ld 创建小型二进制文件?