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:
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 '
:
$input = preg_replace('/\s*,\s*(?!.*,)/',' and ',$input);
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:
$input = preg_replace('/(.*)(?:\s*,\s*)(.*)/','\1 and \2',$input);
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:
$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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.