繁体   English   中英

PHP-添加字符而不是逗号

[英]PHP - Adding a character instead of a comma

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

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

我想要做的是拿出最后一个逗号,并添加一个空格和单词“ and”,因此它显示如下:

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

任何帮助都会很棒。

干杯

一种选择是使用preg_replace匹配最后一个逗号及其周围的空格(如果有),并用' and '代替:

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

看见

说明:

\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);

看见

说明:

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

此处的关键是使用贪婪的正则表达式.*匹配最后一个逗号之前的部分。 贪婪会使.*匹配除最后一个逗号以外的所有逗号。

一种方法:

$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);

用这个

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

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM