I have the following check currently to match if a string is a not a number
if (!ctype_digit($matching)) {
}
however now I wanted to change this such that I wanted to detect the following format:
xxxk
xxxrb
xxx.xxxx
or any numbers
What is the best regular expression to detect this? X here is an integer/digits between 0-9 and it can be any length. So for example, here's a valid match:
8k
72k
123k
899rb
20rb
5rb
160.000
1.600.218
You can use this regex:
^\d{1,3}(?:k|rb|(?:\.\d{3})+|\d+)$
Working demo
The php code is:
$re = "/^\\d{1,3}(?:k|rb|(?:\\.\\d{3})+|\\d+)$/m";
$str = "8k\n72k\n123k\n899rb\n20rb\n5rb\n160.000\n1.600.218";
preg_match_all($re, $str, $matches);
Allow me offer a generic solution based on what I understood about your format.
In Regular Expression you can use | meaning or so based on your multiple format those can be expressed with or's like this:
x{3}k|x{3}rb|x{3}\.x{4}|\d+
Online Demo
Each |(or) represents one of the formats(expression) you may be allowing/evaluating.
Since x is not specify in your post please note x can be easily replaced by letters with [a-zA-Z] expression or by numbers with [0-9] expression or a combination of both like [a-zA-Z0-9].
you can use this:
\A\d+(?:(?:\.\d{3})*|k|rb)\z
Based on the strings you would like to match, here is the regex:
/^\d[0-9a-z\.]+$/i
Working example (please keep in mind that I added the g and m parameters so it would match each example)
If you need to make sure that all decimal points have 3 digits after them then it gets a little more complex:
/^\d{1,3}(?:\.\d{3}?)*(?:[a-z]+)?$/i
More complex example
Update:
Now works according to all new examples.
<?php
$matching = "120.000";
$re = "/^(\b\d{1,3}|k|rb|\.\d{3}\b)*$/";
if (!ctype_digit($matching)) {
if (!preg_match($re, $matching, $matches)) {
echo "ctype_digit/regex not matched";
} else {
echo "regex pattern matched";
}
} else {
echo "ctype_digit matched";
}
?>
Another solution:
\d[.\d]*(?:rb|k)?
Related
I try to make system that can detect date in some string, here is the code :
$string = "02/04/16 10:08:42";
$pattern = "/\<(0?[1-9]|[12][0-9]|3[01])\/\.- \/\.- \d{2}\>/";
$found = preg_match($pattern, $string);
if ($found) {
echo ('The pattern matches the string');
} else {
echo ('No match');
}
The result i found is "No Match", i don't think that i used correct regex for the pattern. Can somebody tell me what i must to do to fix this code
First of all, remove all gibberish from the pattern. This is the part you'll need to work on:
(/0?[1-9]|[12][0-9]|3[01]/)
(As you said, you need the date only, not the datetime).
The main problem with the pattern, that you are using the logical OR operators (|) at the delimiters. If the delimiters are slashes, then you need to replace the tube characters with escaped slashes (/). Note that you need to escape them, because the parser will not take them as control characters. Like this: \/.
Now, you need to solve some logical tasks here, to match the numbers correctly and you're good to go.
(I'm not gonna solve the homework for you :) )
These articles will help you to solve the problem tough:
Character classes
Repetition opetors
Special characters
Pipe character (alternation operator)
Good luck!
In your comment you say you are looking for yyyy, but the example says yy.
I made a code for yy because that is what you gave us, you can easily change the 2 to a 4 and it's for yyyy.
preg_match("/((0|1|2|3)[0-9])\/\d{2}\/\d{2}/", $string, $output_array);
Echo $output_array[1]; // date
Edit:
If you use this pattern it will match the time too, thus make it harder to match wrong.
((0|1|2|3)[0-9])/\d{2}/\d{2}\s+\d{2}:\d{2}:\d{2}
http://www.phpliveregex.com/p/fjP
Edit2:
Also, you can skip one line of code.
You first preg_match to $found and then do an if $found.
This works too:
If(preg_match($pattern, $string, $found))}{
Echo $found[1];
}Else{
Echo "nothing found";
}
With pattern and string as refered to above.
As you can see the found variable is in the preg_match as the output, thus if there is a match the if will be true.
I want to match a keyword using preg_match in php.
regular expression is working perfectly on www.regexr.com but not in my php code. can someone help. Thankyou.
<?php
$regexx="/[sS]+([\s\t\r]*[\.\~\`\!\#\#\$\%\^\&\*\(\)\-\_\+\=\[\]\{\}\;\:\"\'\\\|\,\.\<\>\/\?\d\w]*)+[hH]+([\s\t\r]*[\.\~\`\!\#\#\$\%\^\&\*\(\)\-\_\+\=\[\]\{\}\;\:\"\'\\\|\,\.\<\>\/\?\d\w]*)+[aA]*([\s\t\r]*[\.\~\`\!\#\#\$\%\^\&\*\(\)\-\_\+\=\[\]\{\}\;\:\"\'\\\|\,\.\<\>\/\?\d\w]*)+[rR]*([\s\t\r]*[\.\~\`\!\#\#\$\%\^\&\*\(\)\-\_\+\=\[\]\{\}\;\:\"\'\\\|\,\.\<\>\/\?\d\w]*)+[eE]*
/";
if (preg_match($regexx, "S-hare"))
{
echo 'succeeded';
}
else
{
echo 'failed';
}
?>
Based on your comment:
I want to match the word 'share' written in any format. for example.. any special character or space in between 'share' would be detected.
I would suggest to simply remove every non alphabetics characters then match what is left.
var_dump($str = preg_replace("/[^a-z]/i", "", "sh#a/#~r: e !!!"));
var_dump($str === "share");
A raw single regex solution could be:
/[^a-z]*s[^a-z]*h[^a-z]*a[^a-z]*r[^a-z]*e[^a-z]*/i
Which is simple share and [^a-z]* to match any non alphabetics series of characters between every letters.
So I have a pretty large dump file that I have to extract specific content from it.
The file has record each containing specific numbers enclosed by ". Bellow is a sample part of the file:
Ali Rabi (CustomerId=["3453456"]) // need to get: 3453456
Mohammad Reza Saberi (CustomerId=["12328"]) // need to get: 12328
Currently I read line by line and get the IDs as bellow. the code works fine and I get the result I want:
$cid = substr($row, strpos($row, '[') +2, strpos($row, ']')-strpos($row, '[')-2);
echo $cid;
But doesn't PHP have a function for this? getting the string enclosed by some delimiters?
If all your records look like the ones you've mentioned, I think it's the perfect place where you could use regular expressions.
Regular Expressions help you to create and find patterns in a given String.
For your case, you could probably use :
if (preg_match("/[0-9]+/", "Ali Rabi (CustomerId=[\"3453456\"])", $matches)) {
echo "Match was found <br />";
echo $matches[0];
}
The preg_match() function helps you to find the matches. The first param for this function is the pattern you're looking for. In your case you're looking for a set of continuous digits each of which can range from 0-9.
So, for a single digit we use [0-9]. Adding a + after [0-9] means that there needs to be atleast one digit in the match. Hence, [0-9]+ as the regular expression.
Read more about regular expressions in php : http://webcheatsheet.com/php/regular_expressions.php
Try:
<?php preg_match_all("/([1-9]+)/",$yourtext, $result, PREG_PATTERN_ORDER); ?>
$result contains all Matches.
Further Infomartion: http://php.net/manual/de/function.preg-match-all.php
I think you can use str_replace to remove the "
$cid = str_replace('"','',$row);
I'm having a some trouble formatting my regular expression for my PHP code using preg_match().
I have a simple string usually looking like this:
"q?=%23asdf".
I want my regular expression to only pass true if the string begins with "q?=%23" and there is a character at the end of the 3. So far one of the problems I have had is that the ? is being pulled up by the regex so doing something like
^q?=23 doesn't work. I am also having problems with contiguous searching in Regex expressions (because I can't figure out how to search after the 3).
So for clarification: "q?=%23asd" should PASS and "q?=%23" should FAIL
I'm no good with Regex so sorry if this seems like a beginner question and thanks in advance.
Just use a lookahead to check whether the character following 3 is an alphabet or not,
^q\?=%23(?=[a-zA-Z])
Add . instead of [A-Za-z] only if you want to check for any character following 3,
^q\?=%23(?=.)
Code would be,
$theregex = '~^q\?=%23(?=[a-z])~i';
if (preg_match($theregex, $yourstring)) {
// Yes! It matches!
}
else { // nah, no luck...
}
So the requirement is: Start with q?=%23, followed by at least one [a-z], the pattern could look like:
$pattern = '/^q\?=%23[a-z]+/i';
Used i (PCRE_CASELESS) modifier. Also see example at regex101.
$string = "q?=%23asdf";
var_dump(figureOut($string));
function figureOut($string){
if(strpos($string, 'q?=%23') == 0){
if(strlen($string) > 6){
return true;
}else{ return false;}
}
}
I am having the dang-est time trying to write a regex that will extract the phone extension from a full phone number string. This should work on a number like this one: 777.777.7777 x 7302
It should also work using "ext", "EXT", "Ext", "eXt", "ext.", and "Ext ". Essentially just cover all the common ground use of it.
I just need the "x 7302" part. In fact I am just going to strip it down to just the extension number once I extract it.
Can anyone help me please? Regular expressions are something that I struggle with when they get more complex.
I am doing this in a PHP function (preg_match) if that will help anyone.
This probably helps to give you something to play with:
$phonenumber = '777.777.7777 x 7302';
$extension = preg_replace('(^.*(ext|x) ?([0-9]+)$)i', '$2', $phonenumber);
echo $extension;
Use the i modifier (at the end) to make the regex case insensitive so to match all combinations of ext. I used a group to offer both variant: ext or x: (ext|x).
The rest is looking for a number at the end, and a space is possible between EXT and the number.
try with regex:
/e?xt?\.?\s*\d+$/i
<?
echo "<pre>";
$phone = '777.777.7777 x 7302';
preg_match("/e?xt?\.?\s*\d+$/i", $phone, $matched);
print_r($matched);
?>
Output:
Array
(
[0] => x 7302
)
\w+\s*\d+$
It is an simpler regex assuming that the input is similar to what you have provided.
This should do it for you
/([\d\-\.]+)([ext\. ]+)(\d+)/i
The first set matches the numbers separated by dash or dot. The second set matches your extension string and the third set matches your extension number.
If you just want the last numbers of the string, you can use:
\D+(\d+)$
\D+ at least one non-digit followed by:
(\d+) at least one digit (captured using parenthesis)
$ at the end of the string.
I am a bit leery of regular expression, so I'm a bit biased when I say, is it possible to just split the string using the PHP function "explode()", using the 'x' character as your delimiter?
Here is a link to the PHP manual for that function if you are not familiar with it:
Explode()
Try this function:
$pn = "777.777.7777 x 7302";
function get_ext($pn)
{
$ext = preg_replace('/[\d\.\s]+[ext\s]+(\d{1,})/i', '$1', $pn);
return $ext;
}
echo get_ext($pn);
//7302