PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How can I move chinese characters in a string to the end of string?

 November 20, 2022     oop, php, preg-replace     No comments   

Issue

I have a string like this now: I want to do the following in PHP:

$string = 'Testing giving dancing 喝 喝 passing 制图 giving 跑步 吃';

I want to move all Chinese characters to the end of the string, and also reversing their current order. Accordingly, Removing the duplicate English words and Return the modified string


Solution

Here you go! Check the comments in the code:

<?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 吃 跑步 制图 喝

See it here! https://3v4l.org/FWQWG



Answered By - delboy1978uk
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing