简体   繁体   中英

How to replace only one character, and the last of the string

I need to make like a str_replace() but with only one character, and must be the last character of the string.

For example, if I have:

$var = "one,two,three,four,finish";

I need to be returned:

"one,two,three,fourfinish";

I need to replace the last , of the string.

I know it might be easy but I didn't find anything clear on the net!

You can use strrpos to find the last occurrence of a string in a string, and then use substr :

<?php
    $var = "one,two,three,four,finish";

    if ($lastPosition = strrpos($var, ',')) {
        $var = substr($var, 0, $lastPosition) . substr($var, $lastPosition + 1);
    }

    var_dump($var); //string(24) "one,two,three,fourfinish"
?>

DEMO


If you want to replace it, you just have to concat the replacing string in your condition:

<?php
    $var = "one,two,three,four,finish";
    $replace = "-";

    if ($lastPosition = strrpos($var, ',')) {
        $var = substr($var, 0, $lastPosition) . $replace . substr($var, $lastPosition + 1);
    }

    var_dump($var); //string(24) "one,two,three,four-finish"
?>

Find the location of the last comma in the string using strrpos() and remove it using substr_replace() :

echo substr_replace($var, '', strrpos($var, ','), 1);

Demo

If the last word of $var always is "finish", you could use this:

$var = "one,two,three,four,finish";
$goodVar = str_replace(',finish', 'finish', $var);
print $goodVar;

Try this.

$string = 'one,two,three,four,finish';
$find = ',';
$replace = '';
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
echo strrev($result);
$var = "one,two,three,four,finish";

$var = preg_replace("/,([^,]*)$/", "\\1", $var);

// $var: "one,two,three,fourfinish"

You can use strchr to find the last occurence of a character in a given string

Try

$var = "one,two,three,four,finish";
$len =  strlen($var)-strlen(substr(strrchr($var,","),1));
echo  substr($var,0,$len-1).substr(strrchr($var,","),1);

Demo here

You can find last offset for the char "," with strrpos. Then cut and merge.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM