Travis
Travis

Reputation: 687

PHP Checking if a numbered string follows a pattern

I am comparing inputs of different version numbers looking like so:

testname-v01.03.001.01
testname-v02.01.001.03
...

I am doing a comparison to make sure that no inputs are being maliciously entered into my textbook to harm my sql tables.

What I am doing is something like this:

<?php
    function startsWith($needle, $haystack){
        return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
    }
    $reqmethod = $_SERVER["REQUEST_METHOD"];
    $textInput = "";
    if( $reqmethod == "GET") {
        $textInput = $_GET["my_input"];
    }
    $stringComparison = "v02.01.001.01";
    if ( $textInput != ""){
        $valid_input = startsWith("testname", $textInput); #See if text starts with version
        #if not check if its a partial match
        if (!$valid_input){
            if(preg_match('/^[A-Z][0-9]+.[0-9].[0-9].[0-9]', $textInput)){
            $textInput= "version-" + $textInput;
        } else {
            $textInputReadOut = "BAD VALUE";
            $textInput= "";
        }
    }
?>

To get the preg_match to equal say v01 would I just go about that by doing something like this: [A-Z][0-9][0-9]? I have tried that but the variable returns a BAD VALUE instead

Referenced : Checking a string against a pattern

Upvotes: 0

Views: 103

Answers (2)

SirPilan
SirPilan

Reputation: 4857

Have a look at your regex:

if(preg_match('/^[A-Z][0-9]+.[0-9].[0-9].[0-9]', $textInput)){

you are missing the closing /

It has to be:

if(preg_match('/^[A-Z][0-9]+.[0-9].[0-9].[0-9]/', $textInput)){

And here the corrected version:

^[a-zA-Z][0-9]{2}\.[0-9]{2}\.[0-9]{3}\.[0-9]{2}

You can use tools like regexr to test your regex.

Upvotes: 1

Charles Stover
Charles Stover

Reputation: 1148

Your regular expression is matching strings that start with (^) v1.2.3.4, but your $textInput starts with testname (or presumably other package names).

You also have it coded that the regular expression only checks if the input is invalid. Your text input is always valid, because it always starts with testname, meaning you always land in your else wherein the output is BAD VALUE. Any time your $textInput starts with testname, the output is BAD VALUE, as far as your code is currently concerned.

Upvotes: 0

Related Questions