在php中反转每个单词时出错
我正试图反转每个单词的字符串,这里是我的逻辑,任何人都可以检查并纠正我出错的地方。必须感谢我知道我遗漏了一些东西。如果要编写此代码和逻辑,请务必理解 代码:-在php中反转每个单词时出错,php,Php,我正试图反转每个单词的字符串,这里是我的逻辑,任何人都可以检查并纠正我出错的地方。必须感谢我知道我遗漏了一些东西。如果要编写此代码和逻辑,请务必理解 代码:- <?php $a = "i am getting late"; $count = 0; $Reversestring = ""; while(isset($a[$count])) { if($a[$count] != '') { echo $a[$count]; $catchWord .
<?php
$a = "i am getting late";
$count = 0;
$Reversestring = "";
while(isset($a[$count]))
{
if($a[$count] != '')
{
echo $a[$count];
$catchWord .= $a[$count];
$count++;
}else{
die($catchWord);
$Reversestring .= reverseWord($catchWord);
}
}
echo $Reversestring;
function reverseWord($word)
{
$revWord;
for($i = str_word_count($word) ; $i > 0; $i--)
{
$revWord = $word[$i];
}
return $revWord;
?>
函数的问题是在新字符串的末尾添加字符
$str.=$foo
在$str
的末尾追加$foo
。您希望在它前面加上前缀以实际反转字符串
使用内置功能
PHP已经有了内置函数来完成这项任务。您可以简化逻辑并使用以下解决方案,而不是修改函数。为什么要重新发明轮子
$result = array_map(function ($item) {
return strrev($item);
}, explode(' ', $a));
$reversed = implode(' ', $result);
不使用内置功能
如果不想使用内置函数,则可以使用以下解决方案。代码来自:
试试这个
$str = "Iam New Here";
$spaceCount = substr_count($str, " ");
$letterIndx = 0;
// count number of spaces and then loop
for($i=0; $i<=$spaceCount; $i++) {
// get space positions
$spaceIndx = strpos($str, " ", $letterIndx);
// assign word by specifying start position and length
if ($spaceIndx == 0) {
$word = substr($str, $letterIndx);
} else {
$word = substr($str, $letterIndx, $spaceIndx - $letterIndx);
}
// push word into array
$myArray[] = $word;
// get first letter after space
$letterIndx = $spaceIndx + 1;
}
// reverse the array
$reverse = array_reverse($myArray);
// echo it out
foreach($reverse as $rev) {
echo $rev." ";
}
$str=“Iam New Here”;
$spaceCount=substr\u count($str,“”);
$letterIndx=0;
//计算空格数,然后循环
对于($i=0;$i)您是否打算在reverseeword
函数中使用=
而不是=
?这可能与此问题重复。实际上,根据我的逻辑,我不想使用问题中提到的任何内置函数。
i ma gnitteg etal
$str = "Iam New Here";
$spaceCount = substr_count($str, " ");
$letterIndx = 0;
// count number of spaces and then loop
for($i=0; $i<=$spaceCount; $i++) {
// get space positions
$spaceIndx = strpos($str, " ", $letterIndx);
// assign word by specifying start position and length
if ($spaceIndx == 0) {
$word = substr($str, $letterIndx);
} else {
$word = substr($str, $letterIndx, $spaceIndx - $letterIndx);
}
// push word into array
$myArray[] = $word;
// get first letter after space
$letterIndx = $spaceIndx + 1;
}
// reverse the array
$reverse = array_reverse($myArray);
// echo it out
foreach($reverse as $rev) {
echo $rev." ";
}