2012-03-27 14 views
8

文字列を2つの部分に分割する必要があります。文字列がスペースで区切られた単語が含まれており、単語の任意の数、例えば含めることができます:最初の部分は最後のものを除いて、すべての単語が含まれている必要があり文字列を2つの部分に分割する

$string = "one two three four five";

を。 2番目の部分は最後の単語だけを含む必要があります。

誰も助言できますか?

EDIT:2つの部分は例えば、文字列ではなく配列として返される必要があります。

$part1 = "one two three four";

$part2 = "five";

+1

strrposが良い出発点になります。マニュアルには多くのものがあります。 – GordonM

答えて

21

カップルの方法区切り文字列によって形成された境界にそれを分割することによって、あなたはそれについて移動することができます。

配列操作:

$string ="one two three four five"; 
$words = explode(' ', $string); 
$last_word = array_pop($words); 
$first_chunk = implode(' ', $words); 

文字列操作:

$string="one two three four five"; 
$last_space = strrpos($string, ' '); 
$last_word = substr($string, $last_space); 
$first_chunk = substr($string, 0, $last_space); 
+0

論理的には、OPは文字列を使用していて配列を使用していないので、配列を必要としないので、 "非"配列オプションを使用するといいでしょう(コードは文字列でのみ機能するので、パフォーマンスの違いはありますか? – James

7

必要なものは、最後のスペース上の入力文字列を分割することです。今度は最後のスペースは、それ以上のスペースがないスペースです。だから、最後のスペースを見つけるために、負の先読みアサーションを使用することができます。

$string="one two three four five"; 
$pieces = preg_split('/ (?!.*)/',$string); 
+0

清潔でシンプル! +1 –

5

はPHP

explode機能を見に形成され文字列の部分文字列であるそれぞれの文字列の配列を返します持っています

1
$string = "one two three four five"; 
$array = explode(" ", $string); // Split string into an array 

$lastWord = array_pop($array); // Get the last word 
// $array now contains the first four words 
2
$string="one two three four five"; 

list($second,$first) = explode(' ',strrev($string),2); 
$first = strrev($first); 
$second = strrev($second); 

var_dump($first); 
var_dump($second); 
1

これはそれを行う必要があります。

$arr = explode(' ', $string); 
$second = array_pop($arr); 
$result[] = implode(' ', $arr); 
$result[] = $second; 
1

使用strrpos最後の空白文字の位置を取得するには、その後、その位置で文字列を分割するには、を使用します。

<?php 
    $string = 'one two three four five'; 
    $pos = strrpos($string, ' '); 
    $first = substr($string, 0, $pos); 
    $second = substr($string, $pos + 1); 
    var_dump($first, $second); 
?> 

Live example

1

それは特にエレガントではありませんが、このような何かが、それを行うだろう。

$string=explode(" ", $string); 
$new_string_1=$string[0]." ".$string[1]." ".$string[2]." ".$string[3]; 
$new_string_2=$string[4]; 
1
$string="one two three four five"; 
$matches = array(); 
preg_match('/(.*?)(\w+)$/', $string, $matches); 
print_r($matches); 

出力:

Array ([0] => one two three four five [1] => one two three four [2] => five)

次に、あなたの部分はPerlで$matches[1]$matches[2]

1

私の解決策のようになります。)...PHPとPerlは似ています:) $ string = "one five three four five";

@s = split(/\s+/, $string) ; 

$s1 = $string ; 
$s1 =~ s/$s[-1]$//e ; 

$s2 = $s[-1] ; 
print "The first part: $s1 \n"; 
print "The second part: $s2 \n"; 
関連する問題