PHP regular expression - filter number only
Using is_numeric or intval is likely the best way to validate a number here, but to answer your question you could try using preg_replace instead. This example removes all non-numeric characters:
$output = preg_replace( '/[^0-9]/', '', $string );
Using regex to filter year of fixed length 0 or 4 digit
Try the following:
^([0-9]{4})?$
^
- start of line
([0-9]{4})?
- four numbers, optionally (because of the ?
)
$
- end of line
Using preg_match to filter numbers
This one does the job:
^(?:00|\+)\d{3,}[AF]*$
Explanation:
^ : begining of line
(?: : start non capture group
00 : literally 00
| : OR
\+ : + sign
) : end group
\d{3,} : 3 or more digits
[AF]* : 0 or more letters A or F (change * to + if you want at least one letter)
$ : end of line
In action:
$tests = [
'00123456789123',
'+123456789AAAAA',
'00123FFFFFFFFFF',
'+123AAAAAAFFA',
'ABCD',
'123456F',
'00123B'
];
foreach($tests as $str) {
if(preg_match('/^(?:00|\+)\d{3,}[AF]*$/', $str)) {
echo "$str --> Match\n";
} else {
echo "$str --> NO match\n";
}
}
Output:
00123456789123 --> Match
+123456789AAAAA --> Match
00123FFFFFFFFFF --> Match
+123AAAAAAFFA --> Match
ABCD --> NO match
123456F --> NO match
00123B --> NO match
Trying to filter out non-numeric values with regex in php
You have to use \D
to replace the non digits
$re = "/\\D/";
$str = "76gg7hg67ku6";
$subst = "";
$result = preg_replace($re, $subst, $str);
Just fyi:
\D match any character that's not a digit [^0-9]
\d match a digit [0-9]
Working demo
Regex: Select number only ID from email subject
you just have to remove the carret (^
) which means begining of the line
/\b(4[0-9]{5})\b/
Also to match only 6 digit "words" you have to add \b
which means word boundary.
see https://www.phpliveregex.com/p/pfE
PHP - regex to allow letters and numbers only
1. Use PHP's inbuilt ctype_alnum
You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum
which will do this for you, and execute faster:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo "The string $testcase consists of all letters or digits.\n";
} else {
echo "The string $testcase does not consist of all letters or digits.\n";
}
}
?>
2. Alternatively, use a regex
If you desperately want to use a regex, you have a few options.
Firstly:
preg_match('/^[\w]+$/', $string);
\w
includes more than alphanumeric (it includes underscore), but includes all
of \d
.
Alternatively:
/^[a-zA-Z\d]+$/
Or even just:
/^[^\W_]+$/
String filtering in php with preg_match and regular expression
Yes, the circumflex goes outside the [] to indicate the start of the string, you probably need an asterisk to allow an arbitrary number of characters, and you probably want a $ at the end to indicate the end of the string:
$tv = preg_match('/^[a-z0-9]*$/', $myval);
If you write [^a-z] it means anything else than a-z.
Extract SKU values which may be numeric or alphanumeric and must be 4 to 20 characters long
Until the regex maestros show up, a lazy person such as myself would just do two rounds on this and keep it simple. First, match all strings that are only A-Z
, 0-9
(rather than crafting massive no-lists or look-abouts). Then, use preg_grep()
with the PREG_GREP_INVERT
flag to remove all strings that are A-Z only. Finally, filter for unique matches to eliminate repeat noise.
$str = '-9 Cycles 3 Temperature Levels Steam Sanitizet+ -Sensor Dry | ALSO AVAILABLE (PRICES MAY VARY) |- White - 1258843 - DVE45R6100W {+ Platinum - 1501 525 - DVE45R6100P desirable: 1258843 DVE45R6100W';
$wanted = [];
// First round: Get all A-Z, 0-9 substrings (if any)
if(preg_match_all('~\b[A-Z0-9]{6,24}\b~', $str, $matches)) {
// Second round: Filter all that are A-Z only
$wanted = preg_grep('~^[A-Z]+$~', $matches[0], PREG_GREP_INVERT);
// And remove duplicates:
$wanted = array_unique($wanted);
}
Result:
array(3) {
[2] · string(7) "1258843"
[3] · string(11) "DVE45R6100W"
[4] · string(11) "DVE45R6100P"
}
Note that I've increased the match length to {6,24}
even though you speak of a 4-character match, since your sample string has 4-digit substrings that were not in your "desirable" list.
Edit: I've moved the preg_match_all()
into a conditional construct containing the the remaining ops, and set $wanted
as an empty array by default. You can conveniently both capture matches and evaluate if matched in one go (rather than e.g. have if(!empty($matches))
).
Update: Following @mickmackusa's answer with a more eloquent regex using a lookahead, I was curious over the performance of a "plain" regex with filtering, vs. use of a lookahead. Then, a test case (only 1 iteration at 3v4l to not bomb them, use your own server for more!).
The test case used 100 generated strings with potential matches, run at 5000 iterations using both approaches. Matching results returned are identical. The single-step regex with lookahead took 0.83 sec on average, while the two-step "plain" regex took 0.69 sec on average. It appears that using a lookahead is marginally more costly than the more "blunt" approach.
PHP filter using preg_replace to allow only alphanumerics and some punctuation
$string = ';")<br>kk23?!';
$new_string = preg_replace("/[^A-Za-z0-9.!?]/",'',$string);
echo $new_string;
Leaves: letters, numbers, spaces, .!?
/* 3 choices. Pick one you like! */
$str = preg_replace("/[^A-Za-z0-9.!? ]/","",$str);
$str = preg_replace("/[^A-Za-z0-9.!?\s]/","",$str);
$str = preg_replace("/[^A-Za-z0-9.!?[:space:]]/","",$str);
Related Topics
Strcmp Equivelant for Integers (Intcmp) in PHP
Reflectionexception: Class Classname Does Not Exist - Laravel
How to Redirect to Another Page Using PHP
Php: Setting a Timezone by Utc Offset
How to Customize Fos Userbundle Urls
Codeigniter Session Data Lost After Redirect
Downloading Attachments to Directory with Imap in PHP, Randomly Works
Php: Why Isn't Exec() Returning Output
Replace the Variable Price Range by the Chosen Variation Price in Woocommerce 4+
Laravel $Q->Where() Between Dates
"No Such File or Directory" or "No Such Host Is Known" When Running Migrations
Add PHP Variable Inside Echo Statement as Href Link Address
PHP Multidimensional Array Get Values
Laravel 4 Removing Public from Url
PHP Mail() Attachment Problems
PHP PHP_Network_Getaddresses: Getaddrinfo Failed: No Such Host Is Known