5 Expresiones Regulares Muy Útiles para El Desarrollador Web

5 Expresiones Regulares Muy Útiles para El Desarrollador Web

En Sentido Web han publicado 5 expresiones regulares que nos pueden ser útiles a todos los desarrolladores web y es que con una sola expresion regular bien implementada podemos ahorrarnos varias lineas de código.

Comprobar que una cadena solo contenga carateres alfanumericos y que la longitud este entre 3 y 16.

/^{3,16}$/

[/code]

Ejemplo de Uso en PHP


function validate_username( $username ) {
if(preg_match(‘/^{3,16}$/’, $_GET[‘username’])) {
return true;
}
return false;
}
[/code]

Encontrar una etiqueta XHTML o XML

  • {<tag[^>]*>(.*?)</tag>}

Etiqueta XHTML o XML con atributos

  • {<tag[^>]*attribute\s*=\s*([“‘])value\1[^>]*>(.*?)</tag>}

Verificar Dirección de Correo Electrónico (Email)

function is_valid_email_address($email){
$qtext = ‘[^\x0d\x22\x5c\x80-\xff]’;
$dtext = ‘[^\x0d\x5b-\x5d\x80-\xff]’;
$atom = ‘[^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c’.
‘\x3e\x40\x5b-\x5d\x7f-\xff]+’;
$quoted_pair = ‘\x5c[\x00-\x7f]’;
$domain_literal = “\x5b($dtext|$quoted_pair)*\x5d”;
$quoted_string = “\x22($qtext|$quoted_pair)*\x22”;
$domain_ref = $atom;
$sub_domain = “($domain_ref|$domain_literal)”;
$word = “($atom|$quoted_string)”;
$domain = “$sub_domain(\x2e$sub_domain)*”;
$local_part = “$word(\x2e$word)*”;
$addr_spec = “$local_part\x40$domain”;

return preg_match(“!^$addr_spec$!”, $email) ? 1 : 0;
}

[/code]

Validar URL?

{
\b
# Match the leading part (proto://hostname, or just hostname)
(
# http://, or https:// leading part
(https?)://[-\w]+(\.\w[-\w]*)+
|
# or, try to find a hostname with more specific sub-expression
(?i: (?:[-a-z0-9]*)? \. )+ # sub domains
# Now ending .com, etc. For these, require lowercase
(?-i: com\b
| edu\b
| biz\b
| gov\b
| in(?:t|fo)\b # .int or .info
| mil\b
| net\b
| org\b
| \.\b # two-letter country code
)
)

# Allow an optional port number
( : \d+ )?

# The rest of the URL is optional, and begins with /
(
/
# The rest are heuristics for what seems to work well
[^.!,?;”‘<>()[]{}sx7F-\xFF]*
(
[.!,?]+ [^.!,?;”\’<>()\[\]{\}s\x7F-\xFF]+
)*
)?
}ix

[/code]