PHP - 添加字符而不是逗号

时间:2011-02-01 05:05:46

标签: php

我有以下字符串,这是从数据库写的,所以我不确定这些值是什么,但是一个例子是

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

我想要做的是取出最后一个逗号并添加一个空格和单词'和',使其显示如下:

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

任何帮助都会很棒。

干杯

4 个答案:

答案 0 :(得分: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.

或者,您可以将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

这里的关键是使用贪婪的正则表达式.*来匹配最后一个逗号之前的部分。贪婪会使.*与最后一个逗号匹配。

答案 1 :(得分: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);

答案 2 :(得分:0)

使用此

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

答案 3 :(得分: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);