Regular expression, PHP

2

What is the correct way to validate the string for the nomenclature below, using regular expression?

/filmes/todos-filmes/notas-espectadores/?page=[SÓ NUMEROS]

    
asked by anonymous 22.01.2017 / 23:44

3 answers

5

Basically this:

/filmes/todos-filmes/notas-espectadores/\?page=\d+

The backslash before ? is because ? alone is a special character.

The \d means "digit", and the + then means "one or more", ie it must have one or more digits to be valid.


Applying to Your Case:

$padrao='~/filmes/todos-filmes/notas-espectadores/\?page=\d+~';

if preg_match($padrao, $endereco) {
   ...

See working at IDEONE .


When using in the following code, we set ~ to the "ends" of the string . They are not part of the expression, they are the delimiters, which separate the contents of the flags when they exist. It is very common to use / as a delimiter, but since the text already has bars, ~ is different enough to not confuse. The syntax is:

    delimitador expressão delimitador flags

Example:

    /\d+/i

In this case the expression is only \d+ and the flag is i . The / are just to separate. The first character used is to indicate which is the delimiter, and the next occurrence of it indicates the end of the expression.

    
22.01.2017 / 23:46
0

Assuming the expected behavior for an invalid parameter is 404. I recommend forgetting regular expression and doing this:

  $page = (int)$_GET['page'];
  if ($page==0) {
      header("HTTP/1.0 404 Not Found");
  }
    
22.01.2017 / 23:47
0

Exactly in this case it would be:

preg_match('/(?:page[\=]([0-9]+))/i', $_SERVER['REQUEST_URI'], $resultado);


if((isset($resultado[1]) == true) and ($resultado[1] != null)){

echo "Pagina existe! Vamos para lá?!";

} else {

echo "Essa página não existe cara! Elas só vão até 2!";

}

It would only take the numbers in the case, but it is mandatory that before the number has "page=". On my site I do not use Wordpress or any kind of CMS, nor do I even use MVC everything on the website works on the basis of 'regular expressions'. It has a class that keeps an eye on everything that is typed in the URL or clicked and elaborates all the variables and communicates with other classes which in possession of such variables, some global due to their scope, determine how to assemble the page. I find regular expressions "fantastic". Save who invented this.

    
29.01.2017 / 18:02