Preg_match find numbers in string after Dash [duplicate] - php

i have a id like stringNumber variable like the one as follows : example12
I need some javascript regex to extract 12 from the string."example" will be constant for all id and just the number will be different.

This regular expression matches numbers at the end of the string.
var matches = str.match(/\d+$/);
It will return an Array with its 0th element the match, if successful. Otherwise, it will return null.
Before accessing the 0 member, ensure the match was made.
if (matches) {
number = matches[0];
}
jsFiddle.
If you must have it as a Number, you can use a function to convert it, such as parseInt().
number = parseInt(number, 10);

RegEx:
var str = "example12";
parseInt(str.match(/\d+$/)[0], 10);
String manipulation:
var str = "example12",
prefix = "example";
parseInt(str.substring(prefix.length), 10);

Related

Regex to match four blocks ranges [duplicate]

What is the regular expression (in JavaScript if it matters) to only match if the text is an exact match? That is, there should be no extra characters at other end of the string.
For example, if I'm trying to match for abc, then 1abc1, 1abc, and abc1 would not match.
Use the start and end delimiters: ^abc$
It depends. You could
string.match(/^abc$/)
But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'
I think you would want to use \b (word boundaries):
var str = 'the first 3 letters of the alphabet are abc. not abc123';
var pat = /\b(abc)\b/g;
console.log(str.match(pat));
Live example: http://jsfiddle.net/uu5VJ/
If the former solution works for you, I would advise against using it.
That means you may have something like the following:
var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
if (strs[i] == 'abc') {
//do something
}
else {
//do something else
}
}
While you could use
if (str[i].match(/^abc$/g)) {
//do something
}
It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.
More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
"^" For the begining of the line "$" for the end of it. Eg.:
var re = /^abc$/;
Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

How to skip first zero in the entry form in Laravel?

here is field name "phone number". i want to store data in the database table without leading zero when a user can input phone number like '01323442234' or '1323442234'.
input = '01323442234' or '1323442234'
store = '1323442234' (skip first zero)
$trimmed_phone = ltrim($input, "0");
ltrim will trim all the leading character from a string, no other characters will be removed.
doc: https://www.php.net/manual/en/function.ltrim.php
There are a lot of way to remove 0 from the first part of a string.
If it contains only number, then cast it to integer
$var = (int)$var;
You can use left trim as follow :
$var = ltrim($var, '0');
Just use + inside variables:
echo +$var;
Multiple it by 1 :
$var = "0000000000010";
print $var*1; // prints 10
Note : If your string contains without number, then only use ltrim

PHP manipulate string (find/replace if component present)

I need to check a string using PHP for a particular text component and replace the value if it is present with a new value. For example I might have a string like this:
?customerID=12345&recid=65&skip=20&type=job
I need to locate the "&skip=20" (it won't always = 20, it could be any number like 20, 80, 100, etc) substring and replace the "20" value with a new value from a variable ($newValue). So if that string was present and $newValue = 40 the new string would be:
?customerID=12345&recid=65&skip=40&type=job
If the string was:
?customerID=12345&recid=65&skip=160&type=job
the new string would be ($newValue = 180):
?customerID=12345&recid=65&skip=180&type=job
I'm pretty sure I should be using these functions - strpos, preg_match, preg_replace - but I've spent way too long on this and don't appear to be getting any closer. If anyone can show me how to use these or other functions to find the substring and replace the value that would be much appreciated.
Try preg_replace_callback
<?php
$str = "?customerID=12345&recid=65&skip=20&type=job";
$newStr = preg_replace_callback("/skip=([0-9]+)/i", "doIt", $str)
function doIt($match){
return $match[1] + 20;
}

how to use regular expression for this below stuff in php

I have a database of more than 70000 records and its primary key value started from 1 single digit.
So I want user have to type nm0000001 instead of 1 in url.And in code part I have to discard the rest of the value except 1.
But my problem is i want this type of things having 9 letters in the string and the pattern is like this
1 - nm0000001
9 - nm0000009
10 - nm0000010
2020 - nm0002020
And from the above pattern i want only the digits like 1,9,10,2020 in php.
Here:
$i = (int)substr($input, 2);
No reason to use regexes at all.
Anyway, if you're insisting on using regexp, then:
$input = 'nm0002020';
preg_match('~0*(\d+)$~', $input, $matches);
var_dump($matches[1]);
Assuming the value is received in the URL as a querystring parameter, that is, passed via $_GET['id'] or some other name than id:
// Trim the "nm" off the front
$pk = substr($_GET['id'],2);
// And parse out an integer value.
$id = intval($pk);
There's absolutely no use for regular expressions in this -- use sprintf("nm%07d", ...) to format and just substr and a cast to int to parse.
This function will do the trick:
function extractID($pInput)
{
$Matches = array();
preg_match('/^nm0*(.*)$/', $pInput, $Matches);
return intval($Matches[1]);
}
Here's why /^nm0+(.*)$/ works:
The line must start (^) with exactly one nm
The pattern must continue with at least one 0
At the first non-zero character after nm0..., capture the value (that's the job of the parentheses)
Continue until the end of the line ($)

Regex - Strip non numeric and remove cents if any

I'm currently working on a project in PHP and I'm in need of some Regex help. I'd like to be able to take a user inputted monetary value and strip all non numeric and decimal places/cents.
Ex:
'2.000,00' to '2000'
'$ 2.000,00' to '2000'
'2abc000' to '2000'
'2.000' to 2000
(I'm using non US currency formatting)
How can I do this? I'd appreciate the help - Thanks
You can do:
$str = preg_replace('/[^0-9,]|,[0-9]*$/','',$str);
$output = preg_replace('/[^0-9]/s', '', $input);
that should replace non numeric chars with empty strings.
This should do what you want.
$your_string_without_letters = preg_replace('\w+', '', $your_string)
preg_match('[0-9][0-9.]*', $your_string_without_letters, $matches);
$clean_string = $matches[0];
The match will start as soon as the first number is found, and stop when it hits something that is neither a number nor a dot (ie. a comma or the end of the string in your examples)
EDIT : forgot to remove the letters inside the value first.
(Just a personal opinion, but if a user writes chracters that are not numbers, dots, commas or currency symbols I would refuse the input instead of trying to clean it)
On the client side I use classes on the inputs:
$("input.intgr").keyup(function (e) { // Filter non-digits from input value.
if (/\D/g.test($(this).val())) $(this).val($(this).val().replace(/\D/g, ''));
});
$("input.nmbr").keyup(function (e) { // Filter non-numeric from input value.
var tVal=$(this).val();
if (tVal!="" && isNaN(tVal)){
tVal=(tVal.substr(0,1).replace(/[^0-9\.\-]/, '')+tVal.substr(1).replace(/[^0-9\.]/, ''));
var raVal=tVal.split(".")
if(raVal.length>2)
tVal=raVal[0]+"."+raVal.slice(1).join("");
$(this).val(tVal);
}
});
$("input.money").keyup(function(){ money($(this)) })
.blur(function(){ money($(this),1); });
//----------- free-standing functions --------------
function money($inElem,inBlur,inDec){//enforces decimal - only digits and one decimal point. inBlur bool for final slicing to sets of 3 digits comma delimted
var isBlur=inBlur||0;//expects boolean (true/false/0/1 all work), default to 0 (false)
var dec=inDec || 2;
if(/[^,.0-9]/g.test($inElem.val()))//if illegal chars, remove and update
$inElem.val($inElem.val().replace(/[^,.0-9]/g, ""));
var ra=$inElem.val().split(".");
if(ra.length>2 || ra.length>1 && ra[ra.length-1].length>2){//if too more than 1 "." or last segment more than dec digit count, fix and update
if(ra[ra.length-1].length>2) ra[ra.length-1]=ra[ra.length-1].substr(0,dec);//shorten last element to only dec digit count
$inElem.val(ra.slice(0,ra.length-1).join("")+"."+ra[ra.length-1]);//glom all but last elem as single, concat dec pt and last elem
}
if(inBlur){
ra=$inElem.val().split(".");
var rvsStr=zReverse(ra[0].replace(/,/g,""));
var comDelim="";
while(rvsStr.length>0){
comDelim+=rvsStr.substr(0,3)+",";
rvsStr=rvsStr.substr(3);
}
$inElem.val(zReverse(comDelim).substr(1)+(ra.length==2?"."+ra[1]:""));
}
}
function zReverse(inV){//only simple ASCII - breaks "foo 𝌆 bar mañana"
return inV.split("").reverse().join("");
}

Categories