2013-07-27 16 views
6

達成するためには理想的には何が問題なのでしょうか。文字列の最後の単語の前にコンマを置き換えてください。

私がしようとしているのは、&の最後の単語の前に', 'を置き換えることです。

だから、基本的$ddd内の単語がより存在する場合& DDDとしてそれを必要と$ddd場合& CCC

理論的に話すよりも空になって、私はaciveする必要があることは以下の通りです:

「AAA、BBB、 CCC & DDD」全4つのワードが空でない 『AAA、BBB & CCC』 3が空でないと、最後の一つは とき 『』 2が空でない場合及び2つの最後の言葉は 空である 『AAA & BBB AAA』場合1つだけがretuです空ではない。これは私が上記の記述しようとしたものを作成するだけの試みがあるので、

はここで、私のスクリプト

$aaa = "AAA"; 
    $bbb = ", BBB"; 
    $ccc = ", CCC"; 
    $ddd = ", DDD"; 
    $line_for = $aaa.$bbb.$ccc.$ddd; 
$wordarray = explode(', ', $line_for); 
if (count($wordarray) > 1) { 
    $wordarray[count($wordarray)-1] = '& '.($wordarray[count($wordarray)-1]); 
    $line_for = implode(', ', $wordarray); 
} 

私を判断しないでくださいです。

+2

ここで誰もあなたを判断しません。あなたの質問は大丈夫です。あなたは、あなたが望むもの、試したもの、そしてうまくいかないものを記述しました。私の+1。 –

+0

'$ aaa'、' $ bbb'などの変数は本当にカンマとスペースで始まりますか?それとも、あなた自身でそれらの文字を追加しましたか? –

+0

私は自分ですべてを追加しましたが、実際に例を挙げるには – AlexB

答えて

0

私はこれがあると思いますそれを行う最善の方法:

function replace_last($haystack, $needle, $with) { 
    $pos = strrpos($haystack, $needle); 
    if($pos !== FALSE) 
    { 
     $haystack = substr_replace($haystack, $with, $pos, strlen($needle)); 
    } 
    return $haystack; 
} 

と同じように使用できます:

$string = "AAA, BBB, CCC, DDD, EEE"; 
$replaced = replace_last($string, ', ', ' & '); 
echo $replaced.'<br>'; 
+0

"インターネット上で見つかった機能" ---開発者であり、そのような些細な4行の関数を書くことができず、Googleのためにgoogleすることができない場合、reeeeeeeeally sadでなければならない。 – zerkms

+0

これは私のものではない機能の形で答えますか? – Starx

+0

@zerkms、Ouch !!!! – Starx

6

はここarray_pop()を使用して、この上の私の感想です助けてください:ここでは

$str = "A, B, C, D, E"; 

$components = explode(", ", $str); 

if (count($components) <= 1) { //If there's only one word, and no commas or whatever. 
    echo $str; 
    die(); //You don't have to *die* here, just stop the rest of the following from executing. 
} 

$last = array_pop($components); //This will remove the last element from the array, then put it in the $last variable. 

echo implode(", ", $components) . " &amp; " . $last; 
0

は別の方法である:機能をコピーしたい人にとって、

$str = "A, B, C, D, E"; 
$pos = strrpos($str, ","); //Calculate the last position of the "," 

if($pos) $str = substr_replace ($str , " & " , $pos , 1); //Replace it with "&" 
//^This will check if the word is only of one word. 

、ここで1は次のようになります。 )

function replace_last($haystack, $needle, $with) { 
    $pos = strrpos($haystack, $needle); 
    return $pos !== false ? substr_replace($haystack, $with, $pos, strlen($needle)) : $haystack; 
} 
1

正規表現ベースのソリューション:

$str = "A, B, C, D, E"; 

echo preg_replace('~,(?=[^,]+$)~', '&amp;', $str); 

正規表現の説明:アサーションの

, -- a comma 
(?=[^,]+$) -- followed by one or more any characters but `,` and the end of the string 

ドキュメント(肯定先読み(?= ...)が私の答えに使用された):http://www.php.net/manual/en/regexp.reference.assertions.php

+0

少し説明することができます、私はこれを理解したい。 – Starx

+0

@Starx: – zerkms

関連する問題