簡體   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