2011-02-01 40 views
1

我有以下字符串,这是写弗罗马数据库,所以林不知道的值,而是一个例子是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. 

Alternati 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 2011-02-01 05:08:46

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); 
相关问题