php – How to support letters, numbers, periods and hyphens with a regular expression?

Question:

I need that in a form field only letters, numbers, underscores, dashes and periods can be typed, but not other types of signs, such as " *, >, <, = "
I am trying to do it with the following regular expression, but it fails: "/[a-zA-Z0-9]/" , this should be correct, since I indicate that I only want alphanumeric, however it fails because it also admits strange signs (Special characters) , and I don't know how to exclude them

Answer:

You can create a character class that matches any character except the ones you want to allow ( negation ). You define the oninput event (for example) on the corresponding element when loading its DOM. For the case at hand, the code may be similar to the following:

var textoInput = document.getElementById("texto");

textoInput.oninput = function(event) {
  textoInput.value = textoInput.value.replace(/[^0-9a-zA-ZáéíñóúüÁÉÍÑÓÚÜ_-]/g, "");
};
<input id="texto" placeholder="Texto" maxlength="20">
Scroll to Top