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.
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 am trying to strip away all non-allowed characters from a string using regex. Here is my current php code
$input = "👮";
$pattern = "[a-zA-Z0-9_ !##$%^&*();\\\/|<>\"'+\-.,:?=]";
$message = preg_replace($pattern,"",$input);
if (empty($message)) {
echo "The string is empty";
}
else {
echo $message;
}
The emoji gets printed out when I run this when I want it to print out "The string is empty.".
When I put my regex code into http://regexr.com/ it shows that the emoji is not matching, but when I run the code it gets printed out. Any suggestions?
This pattern should do the trick :
$filteredString = preg_replace('/([^-\p{L}\x00-\x7F]+)/u', '', $rawString);
Some sequences are quite rare, so let's explain them:
\p{L} matches any kind of letter from any language
\x00-\x7F a single character in the range between (index 0) and (index 127) (case sensitive)
the u modifier who turns on additional functionality of PCRE that is incompatible with Perl. Pattern and subject strings are treated as UTF-8.
Your pattern is incorrect. If you want to strip away all the characters that are not in the list provided, then you have to use a negating character class: [^...]. Also, currently, [ and ] are being used as delimiters, which means, the pattern isn't seen as a character class.
The pattern should be:
$pattern = "~[^a-zA-Z0-9_ !##$%^&*();\\\/|<>\"'+.,:?=-]~";
This should now strip away the emoji and print your message.
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 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)?
I want a regular expression to validate a nickname: 6 to 36 characters, it should contain at least one letter. Other allowed characters: 0-9 and underscores.
This is what I have now:
if(!preg_match('/^.*(?=\d{0,})(?=[a-zA-Z]{1,})(?=[a-zA-Z0-9_]{6,36}).*$/i', $value)){
echo 'bad';
}
else{
echo 'good';
}
This seems to work, but when a validate this strings for example:
11111111111a > is not valid, but it should
aaaaaaa!aaaa > is valid, but it shouldn't
Any ideas to make this regexp better?
I would actually split your task into two regex:
to find out whether it's a valid word: /^\w{6,36}$/i
to find out whether it contains a letter /[a-z]/i
I think it's much simpler this way.
Try this:
'/^(?=.*[a-z])\w{6,36}$/i'
Here are some of the problems with your original regex:
/^.*(?=\d{0,})(?=[a-zA-Z]{1,})(?=[a-zA-Z0-9_]{6,36}).*$/i
(?=\d{0,}): What is this for??? This is always true and doesn't do anything!
(?=[a-zA-Z]{1,}): You don't need the {1,} part, you just need to find one letter, and i flag also allows you to omit A-Z
/^.*: You're matching these outside of the lookaround; it should be inside
(?=[a-zA-Z0-9_]{6,36}).*$: this means that as long as there are between 6-36 \w characters, everything else in the rest of the string matches! The string can be 100 characters long mostly containing illegal characters and it will still match!
You can do it easily using two calls to preg_match as:
if( preg_match('/^[a-z0-9_]{6,36}$/i',$input) && preg_match('/[a-z]/i',$input)) {
// good
} else {
// bad
}