php 如何反转字符串中的单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2977556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reverse words in a string?
提问by Meow
This question is already asked/answered by other members but my case is a bit different..
其他成员已经提出/回答了这个问题,但我的情况有点不同。
Problem: How to reverse words in a string? You can use strpos(), strlen(), substr() but not other very useful functions such as explode(), strrev() etc.
问题:如何反转字符串中的单词?您可以使用 strpos()、strlen()、substr(),但不能使用其他非常有用的函数,例如explode()、strrev() 等。
This is basically an interview question so I need to demonstrate ability to manipulate strings.
这基本上是一个面试问题,所以我需要展示操作字符串的能力。
Example:
例子:
$string = "I am a boy"
$string = "我是男孩"
Answer:
回答:
"I ma a yob"
“我是个约伯”
Below is my solution that took me 2 days(sigh) but there gotta be more elegant solution. My code looks very long..
下面是我花了 2 天时间的解决方案(叹气),但必须有更优雅的解决方案。我的代码看起来很长..
Thanks in advance!
提前致谢!
My intention:
我的意图:
1. get number of word
2. based on number of word count, grab each word and store into array
3. loop through array and output each word in reverse order
Code:
代码:
<?php
$str = "I am a boy";
echo reverse_word($str) . "\n";
function reverse_word($input) {
//first find how many words in the string based on whitespace
$num_ws = 0;
$p = 0;
while(strpos($input, " ", $p) !== false) {
$num_ws ++;
$p = strpos($input, ' ', $p) + 1;
}
echo "num ws is $num_ws\n";
//now start grabbing word and store into array
$p = 0;
for($i=0; $i<$num_ws + 1; $i++) {
$ws_index = strpos($input, " ", $p);
//if no more ws, grab the rest
if($ws_index === false) {
$word = substr($input, $p);
}
else {
$length = $ws_index - $p;
$word = substr($input, $p, $length);
}
$result[] = $word;
$p = $ws_index + 1; //move onto first char of next word
}
print_r($result);
//append reversed words
$str = '';
for($i=0; $i<count($result); $i++) {
$str .= reverse($result[$i]) . " ";
}
return $str;
}
function reverse($str) {
$a = 0;
$b = strlen($str)-1;
while($a < $b) {
swap($str, $a, $b);
$a ++;
$b --;
}
return $str;
}
function swap(&$str, $i1, $i2) {
$tmp = $str[$i1];
$str[$i1] = $str[$i2];
$str[$i2] = $tmp;
}
?>
回答by thetaiko
$string = "I am a boy";
$reversed = "";
$tmp = "";
for($i = 0; $i < strlen($string); $i++) {
if($string[$i] == " ") {
$reversed .= $tmp . " ";
$tmp = "";
continue;
}
$tmp = $string[$i] . $tmp;
}
$reversed .= $tmp;
print $reversed . PHP_EOL;
>> I ma a yob
回答by ircmaxell
Whoops! Mis-read the question. Here you go (Note that this will split on all non-letter boundaries, not just space. If you want a character not to be split upon, just add it to $wordChars):
哎呀!误读了问题。在这里(请注意,这将在所有非字母边界上拆分,而不仅仅是空间。如果您希望一个字符不被拆分,只需将其添加到$wordChars):
function revWords($string) {
//We need to find word boundries
$wordChars = 'abcdefghijklmnopqrstuvwxyz';
$buffer = '';
$return = '';
$len = strlen($string);
$i = 0;
while ($i < $len) {
$chr = $string[$i];
if (($chr & 0xC0) == 0xC0) {
//UTF8 Characer!
if (($chr & 0xF0) == 0xF0) {
//4 Byte Sequence
$chr .= substr($string, $i + 1, 3);
$i += 3;
} elseif (($chr & 0xE0) == 0xE0) {
//3 Byte Sequence
$chr .= substr($string, $i + 1, 2);
$i += 2;
} else {
//2 Byte Sequence
$i++;
$chr .= $string[$i];
}
}
if (stripos($wordChars, $chr) !== false) {
$buffer = $chr . $buffer;
} else {
$return .= $buffer . $chr;
$buffer = '';
}
$i++;
}
return $return . $buffer;
}
Edit:Now it's a single function, and stores the buffer naively in reversed notation.
编辑:现在它是一个单一的函数,并天真地以相反的符号存储缓冲区。
Edit2:Now handles UTF8 characters (just add "word" characters to the $wordCharsstring)...
Edit2:现在处理 UTF8 字符(只需在$wordChars字符串中添加“单词”字符)...
回答by Coman Teodor
I believe the easiest way would be to insert your string in an array using explode() and than using array_reverse() function. Of course you will have to output the array. For more details on array_reverse() see http://php.net/manual/en/function.array-reverse.php
我相信最简单的方法是使用explode() 而不是使用array_reverse() 函数将字符串插入到数组中。当然,您必须输出数组。有关 array_reverse() 的更多详细信息,请参阅http://php.net/manual/en/function.array-reverse.php
回答by Vishnu Kant Maurya
$str = "Hello how are you";
$teststr = explode(" ",$str);
for($i=count($teststr)-1;$i>=0;$i--){
echo $teststr[$i]." ";
}
Output : you are how hello
回答by Vishnu Sharma
<?php
// Reversed string and Number
// For Example :
$str = "hello world. This is john duvey";
$number = 123456789;
$newStr = strrev($str);
$newBum = strrev($number);
echo $newStr;
echo "<br />";
echo $newBum;
OUTPUT :
first : yevud nhoj si sihT .dlrow olleh
second: 987654321
回答by Louie Miranda
My answer is to count the string length, split the letters into an array and then, loop it backwards. This is also a good way to check if a word is a palindrome. This can only be used for regular string and numbers.
我的答案是计算字符串长度,将字母拆分为一个数组,然后向后循环。这也是检查单词是否为回文的好方法。这只能用于常规字符串和数字。
preg_split can be changed to explode() as well.
preg_split 也可以更改为explode()。
/**
* Code snippet to reverse a string (LM)
*/
$words = array('one', 'only', 'apple', 'jobs');
foreach ($words as $d) {
$strlen = strlen($d);
$splits = preg_split('//', $d, -1, PREG_SPLIT_NO_EMPTY);
for ($i = $strlen; $i >= 0; $i=$i-1) {
@$reverse .= $splits[$i];
}
echo "Regular: {$d}".PHP_EOL;
echo "Reverse: {$reverse}".PHP_EOL;
echo "-----".PHP_EOL;
unset($reverse);
}
回答by Sumit Kumar
Without using any function.
不使用任何功能。
$string = 'I am a boy';
$newString = '';
$temp = '';
$i = 0;
while(@$string[$i] != '')
{
if($string[$i] == ' ') {
$newString .= $temp . ' ';
$temp = '';
}
else {
$temp = $string[$i] . $temp;
}
$i++;
}
$newString .= $temp . ' ';
echo $newString;
Output: I ma a yob
输出:I ma a yob
回答by Sumit Kumar
It could have been done in a much more elegant way if PHP used concatenative syntax :)
如果 PHP 使用连接语法,它可以以更优雅的方式完成:)
{
"" "" 3 roll
{
dup " " ==
{ . . "" }
{ swp . }
ifelse }
foreach .
} "reverse" function
"I am a boy" reverse echo // Prints "I ma a yob"
回答by Glen Solsberry
Edit: You asked for each word to be reversed, but still in "word" order. Something like this might work better:
编辑:您要求颠倒每个单词,但仍按“单词”顺序排列。像这样的事情可能会更好:
$string = "I am a boy!";
$array = explode(" ", $string);
foreach ($array as &$word) {
$word = strrev($word);
}
$rev_string = implode(" ", $array);

