2017-07-14 65 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.....

相關問題