Viewed   100 times

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

Example:

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

 Answers

3

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
 
makis
 
1

This should work:

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

Paste it somewhere like: http://writecodeonline.com/php/ to see it work.

Tuesday, October 11, 2022
 
mjdth
 
5

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
 
ubod
 
3
NSString *str = @"....";  
NSRange lastComma = [str rangeOfString:@"," options:NSBackwardsSearch];

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

edit:

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

function replaceLinks($replacements, $string){
    foreach($replacements as $key=>$val){
        $key=strtolower((string)$key);
        $newReplacements[$key]=array();
        $newReplacements[$key]['id']=$val;
        //strings to make sure the search isn't in front of
        $newReplacements[$key]['behinds']=array();
        //strings to make sure the search isn't behind
        $newReplacements[$key]['aheads']=array();
        //check for other searches this is a substring of
        foreach($replacements as $key2=>$val2){
            $key2=(string)$key2;
            /* 
            //debugging
            $b = ($key=='11 22'&&$key2=='11 22 33');
            if($b){
                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')
                if($pos!=0){
                    $newReplacements[$key]['behinds'][]=substr($key2,0,$pos);
                }
                //it's not at the end ('ford' and 'fords')
                if(($end=$pos+strlen($key))!=strlen($key2)){
                    $newReplacements[$key]['aheads'][]=substr($key2,$end);
                }
            }
        }
    }
    foreach($newReplacements as $key=>$item){
        //negative lookbehind for words or >
        $tmp="/(?<![w>=])";
        //negative lookbehinds for the beginnings of other searches that this search is a subtring of
        foreach($item['behinds'] as $b){
            $tmp.="(?<!$b)";
        }
        //the actual search
        $tmp.="($key)";
        //negative lookaheads for ends of other searches that this is a substring of.
        foreach($item['aheads'] as $a){
            $tmp.="(?!$a)";
        }
        //case insensitive
        $tmp.='/ie';
        $replacementMatches[]=$tmp;
    }
    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 :