开发者

Replacing last x amount of numbers

I have a PHP variable that looks a bit like this:

$id = "01922312";

I need to replace the last two or three numbers with another character. How can I开发者_运维百科 go about doing this?

EDIT Sorry for the confusion, basically I have the variable above, and after I'm done processing it I'd like for it to look something like this:

$new = "01922xxx";


Try this:

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

Result:

01922xxx


You can use substr_replace to replace a substring.

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

Reference:

http://php.net/substr-replace


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

Usage:

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

See it in action here: http://codepad.org/XGyVQ1hk


Strings can be treated as arrays, with the characters being the keys:

$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 output your original number. Now to do stuff with it, treat it as a normal 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!


Just convert to string and replace...

$stringId = $id . '';
$stringId = substr($id, 0, -2) . 'XX';


We can replace specific characters in a string using preg_replace(). In my case, I want to replace 30 with 50 (keep the first two digits xx30), in the $start_time which is '1030'.

Solution:

$start_time = '1030';
$pattern    = '/(?<=\d\d)30/';
$start_time = preg_replace($pattern, '50', $start_time);

//result: 1050
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜