Viewed   100 times

I'm trying to replace the last occurence of a comma in a text with "and" using strrchr() and str_replace().


$likes = 'Apple, Samsung, Microsoft';
$likes = str_replace(strrchr($likes, ','), ' and ', $likes);

But this replaces the entire last word (Microsoft in this case) including the last comma in this string. How can I just remove the last comma and replace it with " and " ?

I need to solve this using strrchr() as a function. That's why this question is no duplicate and more specific.



just provide the answer with function strrchr()

$likes = 'Apple, Samsung, Microsoft';
$portion = strrchr($likes, ',');
$likes = str_replace($portion, (" and" . substr($portion, 1, -1)), $likes);

because strrchr() will

This function returns the portion of string

See Doc here

so we just need only replace the comma symbol should be fine. and the comma will be always the first character when you use strrchr()

See Demo here

Sunday, August 7, 2022

This should work:

$name = "[hi] helloz [hello] (hi) {jhihi}";
echo preg_replace('/[[{(].*?[]})]/' , '', $name);

Paste it somewhere like: to see it work.

Tuesday, October 11, 2022

One way would be:

string = string.replaceAll("^(.*)\.(.*)$","$1!$2");

Alternatively you can use negative lookahead as:

string = string.replaceAll("\.(?!.*\.)","!");

Regex in Action

Monday, December 19, 2022
NSString *str = @"....";  
NSRange lastComma = [str rangeOfString:@"," options:NSBackwardsSearch];

if(lastComma.location != NSNotFound) {
    str = [str stringByReplacingCharactersInRange:lastComma
                                       withString: @" and"];
Wednesday, October 26, 2022


Took me a good while, but here's what I came up with:

function replaceLinks($replacements, $string){
    foreach($replacements as $key=>$val){
        //strings to make sure the search isn't in front of
        //strings to make sure the search isn't behind
        //check for other searches this is a substring of
        foreach($replacements as $key2=>$val2){
            $b = ($key=='11 22'&&$key2=='11 22 33');
                l('strlen $key2: '.strlen($key2));
                l('strlen $key: '.strlen($key));
                l('strpos: '.(strpos($key2,$key)));

            //the second search is longer and the first is a substring of it
            if(strlen($key2)>strlen($key) && ($pos=strpos($key2,$key))!==false){
                //the first search isn't at the start of the second search ('the ford' and 'ford')
                //it's not at the end ('ford' and 'fords')
    foreach($newReplacements as $key=>$item){
        //negative lookbehind for words or >
        //negative lookbehinds for the beginnings of other searches that this search is a subtring of
        foreach($item['behinds'] as $b){
        //the actual search
        //negative lookaheads for ends of other searches that this is a substring of.
        foreach($item['aheads'] as $a){
        //case insensitive
    return preg_replace($replacementMatches,'"<a href="".$newReplacements[strtolower("$1")]["id"]."">$1</a>"' ,$string);


Pass it an array such as the one you were talking about:

$replaceWith = array('ford mustang'=>123,'ford'=>42,'honda'=>324);

and a string:

$string = "That is a very nice ford mustang, if only every other ford was quite as nice as this honda";

echo replaceLinks($replaceWith,$string);

It gives precedence to larger string keys, so if you have ford and ford mustang, it will replace ford mustang with the link.

Not very practical, but might work.

$string = "That is a very nice ford mustang, if only every other ford was quite as nice as this honda";
$remove = array("/(?<![w>])ford mustang(?![w<])/",'/(?<![>w])ford(?! mustang)(?![<w])/',"/(?<![>w])honda(?![<w])/");
$replaceWith = array("<a href='fordmustangID'>ford mustang</a>","<a href='fordID'>ford</a>","<a href='hondaID'>honda</a>");
echo preg_replace($remove, $replaceWith,$string);

I used regular expressions with negative lookaheads and lookbehinds to make sure the portion of the string we're replacing isn't part of an alphanumeric sequence (like 12ford23 or afford) or touching the start or end tag of an element.

Saturday, December 17, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :