简体   繁体   English

PHP-添加字符而不是逗号

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

I have the following string, this is written froma database, so im not sure what the values are, but an example would be 我有以下字符串,这是从数据库写的,所以我不确定这些值是什么,但是一个例子是

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

What i want to do is take out the last comma and add a space and the word 'and' so it appears as follows: 我想要做的是拿出最后一个逗号,并添加一个空格和单词“ and”,因此它显示如下:

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

Any help would be great. 任何帮助都会很棒。

Cheers 干杯

One option is to use preg_replace to match the last comma and its surrounding space(if any) and replace it with ' and ' : 一种选择是使用preg_replace匹配最后一个逗号及其周围的空格(如果有),并用' and '代替:

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

See it 看见

Explanation: 说明:

\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.

Alternatively you can use a greedy regex with preg_match as: 另外,您可以使用带有preg_match的贪婪正则表达式,如下所示:

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

See it 看见

Explanation: 说明:

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

The key here is to use a greedy regex .* to match the part before the last comma. 此处的关键是使用贪婪的正则表达式.*匹配最后一个逗号之前的部分。 The greediness will make .* match all but the last comma. 贪婪会使.*匹配除最后一个逗号以外的所有逗号。

One way to do it: 一种方法:

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

use this 用这个

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

Codaddict's answer is valid, but it's easier to use strrpos if you're not familiar with regexps: 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