Replacing the last number of numbers

I have a PHP variable that looks something like this:

$id = "01922312"; 

I need to replace the last two or three numbers with another character. How can i do this?

EDIT Sorry for the confusion, basically I have the variable above, and after I finished processing it, I would like it to look something like this:

 $new = "01922xxx"; 
+10
php
source share
5 answers

Try the following:

 $new = substr($id, 0, -3) . 'xxx'; 

Result:

  01922xxx 
+29
source share

You can use substr_replace to replace a substring.

 $id = substr_replace($id, 'xxx', -3); 

Link:

http://php.net/substr-replace

+12
source share
 function replaceCharsInNumber($num, $chars) { return substr((string) $num, 0, -strlen($chars)) . $chars; } 

Using:

 $number = 5069695; echo replaceCharsInNumber($number, 'xxx'); //5069xxx 

See here: http://codepad.org/XGyVQ1hk

+2
source share

Strings can be considered as arrays, with the keys being the symbols:

 $id = 1922312; // PHP converts 01922312 => 1 because of that leading zero. Either make it a string or remove the zero. $id_str = strval($id); for ($i = 0; $i < count($id_str); $i++) { print($id_str[$i]); } 

This should print the original number. Now, to do things with it, treat it like a regular array:

 $id_str[count($id_str) - 1] = 'x'; $id_str[count($id_str) - 2] = 'y'; $id_str[count($id_str) - 3] = 'z'; 

Hope this helps!

+2
source share

Just convert to string and replace ...

 $stringId = $id . ''; $stringId = substr($id, 0, -2) . 'XX'; 
+1
source share

All Articles