I am trying to make this pattern work correctly and I just can't make it work it out. Basically, i want to validate a string that can only accept letter, numbers and the following characters: #!?_;:-,.
Here is the source code I have so far:
<?php
$test_string = '1234bcd#!?_;:-,.';
echo preg_match( "/^[a-z0-9#!?_;:,.]{4,12}$/i", $test_string );
?>
You're trying to print an integer, which won't achieve what you're trying to do. Try this:
if( preg_match( "/^[a-z0-9#!?_;:,.]{4,12}$/i", $test_string )) {
echo 'valid string!';
} else {
echo 'invalid!';
}
Note that your regex deems strings to be valid if they are:
Between 4 and 12 characters long
Consist of only alpabetic characters, numbers, and the other characters you've included.
Also note that your input string is supposed to be invalid, not only because it is too long, but because it contains a dash, which is not supported by your regex:
1234bcd#!?_;:-,.
^
No match
To include it in your regex, place it at the end of your character class in the regex:
preg_match( "/^[a-z0-9#!?_;:,.-]{4,12}$/i", $test_string )
^
some of the characters are reserved by regexp such as . ? etc.
use them with backslashes
if( preg_match( "/^[a-z0-9#!\?_;:,\.\-]{4,12}$/i", $test_string )) {
...
}
This pattern works :
$test_string = '1234bcd#!?_;:-,.';
if(preg_match('/^[a-z0-9#!\?_;:,\.\-]{4,12}$/i', $test_string))
{
echo 'Valid';
}
But in this case 1234bcd#!?_;:-,., it won't because the input string length is 16 (not between 4 and 12 characters long).
By the way, always escape meta-characters. You will find the complete list here.
Related
This is the code:
<?php
$pattern =' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$text = "kdaiuyq7e611422^^$^vbnvcn^vznbsjhf";
$text_split = str_split($text,1);
$data = '';
foreach($text_split as $value){
if (preg_match("/".$value."/", $pattern )){
$data = $data.$value;
}
if (!preg_match('/'.$value.'/', $pattern )){
break;
}
}
echo $data;
?>
Current output:
kdaiuyq7e611422^^$^vbnvcn^vznbsjhf
Expected output:
kdaiuyq7e611422
Please help me editing my code error. In pattern there is no ^ or $. But preg_match is showing matched which is doubtful.
You string $text have ^ which will match the begin of the string $pattern.
So the preg_match('/^/', $pattern) will return true, then the ^ will append to $data.
You should escape the ^ as a raw char, not a special char with preg_match('/\^/', $pattern) by the help of preg_quote() which will escape the special char.
There is no need to split your string up like that, the whole point of a regular expression is you can specify all the conditions within the expression. You can condense your entire code down to this:
$pattern = '/^[[:word:] ]+/';
$text = 'kdaiuyq7e611422^^$^vbnvcn^vznbsjhf';
preg_match($pattern, $text, $matches);
echo $matches[0];
Kris has accurately isolated that escaping in your method is the monkey wrench. This can be solved with preg_quote() or wrapping pattern characters in \Q ... \E (force characters to be interpreted literally).
Slapping that bandaid on your method (as you have done while answering your own question) doesn't help you to see what you should be doing.
I recommend that you do away with the character mask, the str_split(), and the looped calls of preg_match(). Your task can be accomplished far more briefly/efficiently/directly with a single preg_match() call. Here is the clean way that obeys your character mask fully:
Code: (Demo)
$text = "kdaiuyq7e611422^^$^vbnvcn^vznbsjhf";
echo preg_match('/^[a-z\d ]+/i',$text,$out)?$out[0]:'No Match';
Output:
kdaiuyq7e611422
miknik's method was close to this, but it did not maintain 100% accuracy given your question requirements. I'll explain:
[:word:] is a POSIX Character Class (functioning like \w) that represents letters(uppercase and lowercase), numbers, and an underscore. Unfortunately for miknik, the underscore is not in your list of wanted characters, so this renders the pattern slightly inaccurate and may be untrustworthy for your project.
I need to check to see if a variable contains anything OTHER than 0-9 and the "-" and the "+" character and the " "(space).
The preg_match I have written does not work. Any help would be appreciated.
<?php
$var="+91 9766554433";
if(preg_match('/[0-9 +\-]/i', $var))
echo $var;
?>
You have to add a * as a quantifier to the whole character class and add anchors to the start and end of the regex: ^ and $ means to match only lines containing nothing but the inner regex from from start to end of line. Also, the i modifier is unnecessary since there is no need for case-insensitivity in this regex.
This should do the work.
if(!preg_match('/^[0-9 +-]*$/', $var)){
//variable contains char not allowed
}else{
//variable only contains allowed chars
}
Just negate the character class:
if ( preg_match('/[^0-9 +-]/', $var) )
echo $var;
or add anchors and quantifier:
if ( preg_match('/^[0-9 +-]+$/', $var) )
echo $var;
The case insensitive modifier is not mandatory in your case.
You can try regex101.com to test your regex to match your criteria and then on the left panel, you'll find code generator, which will generate code for PHP, Python, and Javascript.
$re = "/^[\\d\\s\\+\\-]+$/i";
$str = "+91 9766554433";
preg_match($re, $str, $matches);
You can take a look here.
Try see if this works. I haven't gotten around to test it beforehand, so I apologize if it doesn't work.
if(!preg_match('/^[0-9]+.-.+." ".*$/', $var)){
//variable contains char not allowed
}else{
//variable only contains allowed chars
}
I am trying to verify in PHP with preg_match that an input string contains only "a-z, A-Z, -, _ ,0-9" characters. If it contains just these, then validate.
I tried to search on google but I could not find anything usefull.
Can anybody help?
Thank you !
Use the pattern '/^[A-Za-z0-9_-]*$/', if an empty string is also valid. Otherwise '/^[A-Za-z0-9_-]+$/'
So:
$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
#your string is good
}
Also, note that you want to put a '-' last in the character class as part of the character class, that way it is read as a literal '-' and not the dash between two characters such as the hyphen between A-Z.
$data = 'abc123-_';
echo preg_match('/^[\w|\-]+$/', $data); //match and output 1
$data = 'abc..';
echo preg_match('/^[\w|\-]+$/', $data); //not match and output 0
You can use preg_replace($pattern, $replacement, $subject):
if (preg_replace('/[A-Za-z0-9\-\_]/', '', $string)) {
echo "Detect non valid character inside the string";
}
The idea is to remove any valid chars, if the result is NOT empty do the code.
I have a variable I want to use in a preg_match combined with some regex:
$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-/d.*/", $string)) {
echo "matched";
}
In my pattern I am trying to match using cheese, followed by a - and 1 digit, followed by anything else.
change /d to \d
there is no need to use .*
if your string is defined by user (or may contains some characters (e.g: / or * or ...)) this may cause problem on your match.
Code:
<?php
$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-\d/", $string))
{
echo "matched";
}
?>
You mistyped / for \:
if(preg_match("/$find-\d.*/", $string)) {
The .* is also not really necessary since the pattern will match either way.
for digit, it's \d
if(preg_match("/$find-\d.*/", $string)) {
Here is the regex I currently have (which kind of works):
$regex = '/[\w ]{7,30}/';
My revision looks like what I want, but it does not work at all:
$regex = '^[\w ]{7,30}$';
Here is how I am using the regex:
public function isValid( $value )
{
$regex = '/^[\w ]{7,30}$/';
return preg_match( $regex, $value ) ? true : false;
}
I am trying to match the following:
Any lower/upper case letter
Any digit
Can contain spaces
Cannot contain line breaks or tab space
Minimum of 7 characters
Maximum of 30 characters
Valid inputs:
Testing
Test ing
Test123
Test 123
Test___
Invalid inputs:
Testing#
Testin8+
Tester1&
The first regex will match all valid inputs, as well as invalid (as long as the first four characters are valid, it doesn't care about the rest). The second regex matches nothing.
Try combining both like so:
$regex = '/^[\w ]{7,30}$/';
Don't forget your delimiters:
/^[\w ]{7,30}$/
You're missing the / at the beginning and end.
$regex = '/^[\w ]{7,30}$/';
'/^[\w ]{7,30}$/'
You're missing the delimiters.