/    Sign up×
Community /Pin to ProfileBookmark

Replace/Update the last character of a string

I have a string, say MS987232
I want to replace the last 2 (and only the last 2) with a 1
The result would be MS987231

any help?

Thx

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@QuidamMay 22.2009 — [code=php]
$string = "MS987232"; // Original string
$replacement = "1"; // What you want to replace the last character with

// The final string
$final = substr($string, 0, -1).$replacement;
[/code]
Copy linkTweet thisAlerts:
@iecowboyauthorMay 22.2009 — Quidam,

Thank you, that worked wonderfully.

Question though, do you know how I could replace a different charector specific to it's location?

ie: MS8762HN needs to change to MS8761HN (change the 3rd char from the end to a 1)

Do you have any thoughts on that?

Thank you for your help!
Copy linkTweet thisAlerts:
@MindzaiMay 22.2009 — You want to replace all 2s with 1s?

[code=php]$string = "MS8762HN";
$final = str_replace('2', '1', $string);[/code]

If not you'll need to be more specific about the rules you want to implement for replacement.
Copy linkTweet thisAlerts:
@QuidamMay 23.2009 — [code=php]
// The string
$string = "MS8762HN";

// The replacement
$replacement = "1";

// The character length of your replacement
$length = strlen($replacement);

// The position of the character you want to replace, note that you start counting on 0. You can count backwards aswell.
// $position = 5;
$position = -3;

// The final string
$final = substr_replace($string, $replacement, $position, $length);
[/code]
×

Success!

Help @iecowboy spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...