2011-02-01 11 views
1

fromaデータベースの代わりに文字を追加し、その値が何であるかわからないイムが、一例は、私が何をしたいのかPHP - カンマ私は次の文字列は、これが書かれている

my name, his name, their name, testing, testing 

だろう最後のカンマを取り出し、スペース 'と'を追加すると、次のように表示されます。

my name, his name, their name, testing and testing 

助けがあれば助かります。

乾杯

答えて

1

一つのオプション(もしあれば)、最後のコンマとその周囲の空間に合うようにpreg_replaceを使用して' and 'でそれを置き換えることです:

$input = preg_replace('/\s*,\s*(?!.*,)/',' and ',$input);   

See it

説明:

\s*  : Optional whitespace 
,  : A literal comma 
\s*  : Optional whitespace 
(?!.*,) : Negative lookahead. It says match the previous pattern(a comma 
      surrounded by optional spaces) only if it is not followed 
      by another comma. 

オルタナティvelyあなたが貪欲な正規表現を使用することができますpreg_matchとして:

$input = preg_replace('/(.*)(?:\s*,\s*)(.*)/','\1 and \2',$input); 

See it

説明:

(.*)  : Any junk before the last comma 
(?:\s*,\s*) : Last comma surrounded by optional whitespace 
(.*)  : Any junk after the last comma 

ここで重要なのは、最後のコンマの前の部分に一致するように貪欲な正規表現.*を使用することです。貪欲は.*と最後のカンマ以外はすべて一致します。それを行うには

+0

それは最後のカンマを取り除くだけでしょうか? – Chris

+0

@Chris:はい。私が投稿した理想のリンクを見ることができます。 – codaddict

0

一つの方法:

$string = "my name, his name, their name, testing, testing"; 
$string_array = explode(', ', $string); 

$string = implode(', ', array_splice($string_array, -1)); 
$string .= ' and ' . array_pop($string_array); 
0

使用この

$list="my name, his name, their name, testing, testing"; 
$result = strrev(implode(strrev(" and"), explode(",", strrev($list), 2))); 
echo $result; 
0

Codaddictの答えは有効ですが、正規表現に慣れていないのであれば、それはのstrrposを使用するように簡単です:

$old_string = 'my name, his name, their name, testing, testing'; 
$last_index = strrpos($old_string, ','); 
if ($last_index !== false) $new_string = substr($old_string, 0, $last_index) . ' and' . substr($old_string, $last_index + 1); 
関連する問題