2017-07-14 70 views
-1

我想将字符串的最后一个单词放到新字符串的开头。获取PHP中最后一个单词之前的所有单词

我只有一个解决方案,如果字符串包含不超过2个单词。如何更改我的代码以获得所需的结果,如果该字符串包含可能包含2个或更多的单词。它应该像现在和超过2个单词一样工作2个单词。

$string = 'second first'; 

function space_check($string){ 
    if (preg_match('/\s/',$string)) 
      return true;  
    } 
    if (space_check($string) == true) { 
     $arr = explode(' ',trim($string)); 
     $new_string = mb_substr($string, mb_strlen($arr[0])+1);    
     $new_string.= ' ' . $arr[0]; 
    } 

    echo $new_string; // result: first second 

    $string2 = 'second third first'; 
    echo $new_string; // desired result: first second third (now 'third first second') 

我还需要为+1的解决方案在mb_strlen($arr[0])+1部分,因为我想如果字符串包含例如三个字,它必须是+2等。

+0

对不起,但知道你在问什么 – rtfm

回答

1
// initial string 
$string2 = 'second third first'; 

// separate words on space 
$arr = explode(' ', $string2); 

// get last word and remove it from the array 
$last = array_pop($arr); 

// now push it in front 
array_unshift($arr, $last); 

// and build the new string 
$new_string = implode(' ', $arr); 

这里是working examplerelevantdocs

0

以下是我会做:

<?php 
    $str  = 'This is a string'; 
    $arr  = explode(' ', $str); 
    $lastWord = $arr[count($arr) - 1]; 

它的作用是什么,使用空格作为分隔符爆炸字符串,然后因为计数返回全部项目的一个int,我们可以使用它作为一个重点(如爆炸创建索引,而不是其名称键),但-1断计数为数组从0开始,而不是1

1

您可以通过使用explodearray_pop来做到这一点。

$string = 'This is your string'; 
$words = explode(' ', $string); 

$last_word = array_pop($words); 

array_pop后使用,$words将包含所有的字,除了最后一个。现在你有了字符串,并且你可以在想要的字符串之前轻松地连接$last_word

+1

我喜欢这个解决方案! :) – ThisGuyHasTwoThumbs

+0

谢谢,但是如何将'$ last_word'放在你的解决方案中的一个新字符串中,最后一个字符'$ string'应该在哪里? – Grischa

+1

然后我会参考@ Matteo的回答... –

1

比爆炸更简单的方法是找到最后一个空格的位置和子字符串。

$str = 'second third first'; 
$firstword = substr($str, strrpos($str, " ")+1); 
$rest = substr($str, 0, strrpos($str, " ")); 
echo $firstword . " " . $rest; 

从去年空间直到结束,接下来的SUBSTR打印从开始到最后的空间首先SUBSTR打印。

https://3v4l.org/2BUTc

EDIT;在第一个substr忘记了+1。我之前的代码打印space first.....

相关问题