Extract last N characters from a number
Discuss coding issues, and scripts related to PHP and MySQL.
-
Marius
- Posts: 106
Extract last N characters from a number
Hello,
I want to extract the last three characters from a number, an id.
For example:
Code: Select all
$id ='123456';
$nid ='456'; //this i need
And, if the id has less than three characters:
Code: Select all
$id ='6';
$nid ='006'; //this i need
What php code to use to get that $nid?
Admin
Hello,
You can use in your php code the getNId() function from the following example.
It returns the first or the last $n characters from a number or string.
Code: Select all
//return a number of $n characters from $id
// $n>0 return first $n characters / $n<0 return last $n characters
function getNId($id, $n){
$id = (string)$id;
$id = ($n>0) ? substr($id, 0, $n) : substr($id, $n);
$nr = abs($n) - strlen($id);
if($nr >0) for($i=0; $i<$nr; $i++) $id ='0'.$id;
return $id;
}
$id =123456;
$nid = getNId($id, -3);
echo $nid; // 456
//Examples
echo getNId('abc_xyz', -3); // xyz
echo getNId('11844', 3); // 118
echo getNId(8, -3); // 008
echo getNId(78, -3); // 078
echo getNId(78, 4); // 0078
Similar Topics
-
Extract number and periods from string in php
PHP - MySQL
First post
I have a string with numbers and periods. For example '123456...'
I want to separate 123456 and ... and still get the number and the period in php....
Last post
It's because the dot (.) in regex is any character, while \. is literal dot.
Try the following code:
$matches = null;
$input = '123456...';...
-
How to display in php special characters from mysql
PHP - MySQL
First post
I prefer not to bother you too often but because of my bad English, two accounts have already been blocked on stack overflow.
And I think you are...
Last post
Try this:
- At the beginning of your php script, for example at the beginning of the configuration.php file add the header function for utf-8...
-
Reverse the characters added in text field
JavaScript - jQuery - Ajax
First post
I have the following html and JavaScript code. An input text box and a button.
<input type='text' id='backwards-input'>
<button...
Last post
Try use and study the following code:
<input type='text' id='backwards-input'>
<button id='backwards-button'>Button</button>...
-
Converting a salary input string to number
JavaScript - jQuery - Ajax
First post
I have the following problem:
1. eliminate thousand separators(,) 5,555 to 5555.
2. if the user inputs 55,66 replace , with . and get the value...
Last post
Try the function from the following code:
function salNr(s){
//If there is comma before the last two digit, replace it with dot, else remove...