PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

preg_quote> <preg_match_all
Last updated: Fri, 04 Jul 2008

view this page in

preg_match

(PHP 4, PHP 5)

preg_match — Realizar una comparación de expresión regular

Descripción

int preg_match ( string $patron , string $asunto [, array &$coincidencias [, int $banderas [, int $desplazamiento ]]] )

Busca en asunto por una coincidencia con la expresión regular dada en patron .

Lista de parámetros

patron

El patrón a buscar, como una cadena.

asunto

La cadena de entrada.

coincidencias

Si se entrega el parámetro coincidencias , entonces éste es llenado con los resultados de la búsqueda. $coincidencias[0] contendrá el texto que coincidió con el patrón completo, $coincidencias[1] tendrá el texto que coincidió con el primer sub-patrón en paréntesis capturado, y así sucesivamente.

banderas

banderas puede ser la siguiente bandera:

PREG_OFFSET_CAPTURE
Si es pasada esta bandera, entonces para cada coincidencia encontrada también será devuelto el desplazamiento de la cadena anexa. Note que esto modifica el valor de retorno a una matriz en donde cada elemento es una matriz que consiste de la cadena coincidente en el índice 0 y su desplazamiento de cadena al interior de asunto en el índice 1.

desplazamiento

Normalmente, la búsqueda comienza desde el principio de la cadena de asunto. El parámetro opcional desplazamiento puede ser usado para especificar el lugar alterno desde donde empezar la búsqueda (en bytes).

Note: El uso de desplazamiento no es equivalente a pasar substr($asunto, $desplazamiento) a preg_match() en lugar de la cadena de asunto, ya que patron puede contener aserciones tales como ^, $ o (?<=x). Compare:

<?php
$asunto 
"abcdef";
$patron '/^def/';
preg_match($patron$asunto$coincidenciasPREG_OFFSET_CAPTURE3);
print_r($coincidencias);
?>

El resultado del ejemplo seria:

Array
(
)

mientras que el siguiente ejemplo

<?php
$asunto 
"abcdef";
$patron '/^def/';
preg_match($patronsubstr($asunto,3), $coincidenciasPREG_OFFSET_CAPTURE);
print_r($coincidencias);
?>

producirá

Array
(
    [0] => Array
        (
            [0] => def
            [1] => 0
        )

)

Valores retornados

preg_match() devuelve el número de veces que patron coincide. Este número será 0 (no existe coincidencia) o 1, ya que preg_match() detendrá la búsqueda después de la primera coincidencia. Por el contrario, preg_match_all() continuará hasta llegar al final de asunto . preg_match() devuelve FALSE si ocurre un error.

Registro de cambios

Versión Descripción
4.3.3 El parámetro desplazamiento fue agregado
4.3.0 Se agregó la bandera PREG_OFFSET_CAPTURE
4.3.0 El parámetro banderas fue agregado

Ejemplos

Example #1 Buscar la cadena de texto "php"

<?php
// El caracter "i" después del delimitador del patrón indica una
// busqueda insensible a mayúsculas/minúsculas
if (preg_match("/php/i""PHP es el lenguaje de scripting web de moda.")) {
    echo 
"Se ha encontrado una coincidencia.";
} else {
    echo 
"No se ha encontrado una coincidencia.";
}
?>

Example #2 Buscar la palabra "web"

<?php
/* La secuencia \b en el patrón indica un límite de palabra, así que solo la
 * palabra única "web" coincide, y no una palabra parcial como "webbing" o
 * "cobweb" */
if (preg_match("/\bweb\b/i""PHP es el lenguaje de scripting web de moda.")) {
    echo 
"Se ha encontrado una coincidencia.";
} else {
    echo 
"No se ha encontrado una coincidencia.";
}

if (
preg_match("/\bweb\b/i""PHP es el website del lenguaje de scripting de moda.")) {
    echo 
"Se ha encontrado una coincidencia.";
} else {
    echo 
"No se ha encontrado una coincidencia.";
}
?>

Example #3 Obtener el nombre de dominio de una URL

<?php
// obtener el nombre de host de una URL
preg_match('@^(?:http://)?([^/]+)@i',
    
"http://www.php.net/index.html"$coincidencias);
$host $coincidencias[1];

// obtener los últimos dos segmentos del nombre de host
preg_match('/[^.]+\.[^.]+$/'$host$coincidencias);
echo 
"el nombre de dominio es: {$coincidencias[0]}\n";
?>

El resultado del ejemplo seria:

el nombre de dominio es: php.net

Notes

Tip

No use preg_match() si sólo desea verificiar si una cadena está contenida en otra. Use strpos() o strstr() en su lugar, ya que éstas son alternativas más rápidas.



preg_quote> <preg_match_all
Last updated: Fri, 04 Jul 2008
 
add a note add a note User Contributed Notes
preg_match
Dino Korah AT webroot DOT com
08-Jul-2008 04:11
preg_match and preg_replace_callback doesnt match up in the structure of the array that they fill-up for a match.
preg_match, as the example shows, supports named patterns, whereas preg_replace_callback doesnt seem to support it at all. It seem to ignore any named pattern matched.
Tim
08-Jul-2008 08:01
I made a mistake in my previous post. Mail addresses may of course only be "exotic" in their local parts, not in the domain part. Therefore, an exotic mail address would be "exotic#%$mail@domain.com".
Tim
07-Jul-2008 02:51
For those not so familiar with regex's, I post my algorithmic email validation routine. It can more easily be changed for individual needs than regex's. My function does NOT recognize exotic email addresses as allowed by RFC. (For example, info@exotic%&$#mail.com is a legal email address but not allowed by my function.)
-Tim

<?php
function email_is_valid($email) {
   if (
substr_count($email, '@') != 1)
      return
false;
   if (
$email{0} == '@')
      return
false;
   if (
substr_count($email, '.') < 1)
      return
false;
   if (
strpos($email, '..') !== false)
      return
false;
  
$length = strlen($email);
   for (
$i = 0; $i < $length; $i++) {
     
$c = $email{$i};
      if (
$c >= 'A' && $c <= 'Z')
         continue;
      if (
$c >= 'a' && $c <= 'z')
         continue;
      if (
$c >= '0' && $c <= '9')
         continue;
      if (
$c == '@' || $c == '.' || $c == '_' || $c == '-')
         continue;
      return
false;
   }
  
$TLD = array (
        
'COM',   'NET',
        
'ORG',   'MIL',
        
'EDU',   'GOV',
        
'BIZ',   'NAME',
        
'MOBI''INFO',
        
'AERO''JOBS',
        
'MUSEUM'
     
);
  
$tld = strtoupper(substr($email, strrpos($email, '.') + 1));
   if (
strlen($tld) != 2 && !in_array($tld, $TLD))
      return
false;
   return
true;
}
?>
mailinglist dot php at hydras-world dot com
03-Jul-2008 02:30
The regexp below thinks that the e-mail address:

'me@de.com' is invalid, which it is not.

'/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@
([a-z0-9])([-a-z0-9_])+([a-z0-9])*
(\.([a-z0-9])([-a-z0-9_-])([a-z0-9])+)*$/i'

I modified it and it seems to work for me in my limited tests of it.

YMMV.
brferreira at grad dot ufsc dot br
25-Jun-2008 07:48
Paperweight, this pattern worked fine for me (even for intranet adresses, like "john@localhost"; and also for subdomain emails, like "john@foo.bar.com"):
'/([a-z0-9])([-a-z0-9._])+([a-z0-9])\@
([a-z0-9])([-a-z0-9_])+([a-z0-9])
(\.([a-z0-9])([-a-z0-9_-])([a-z0-9])+)*/i'

but, still, this won't replace the "activation link", that is the better way to check if an e-mail is valid or not.
jonathan dot lydall at gmail dot removethispart dot com
26-May-2008 12:50
Because making a truly correct email validation function is harder than one may think, consider using this one which comes with PHP through the filter_var function (http://www.php.net/manual/en/function.filter-var.php):

<?php
$email
= "someone@domain .local";

if(!
filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo
"E-mail is not valid";
} else {
    echo
"E-mail is valid";
}
?>
Norbert
06-May-2008 05:00
Debian way is:
dpkg-reconfigure locales
Georg
04-Apr-2008 02:36
In addition to reiner-keller's comment about Umlaute using setlocale (LC_ALL, 'de_DE');

To enable 'de_DE' on my Debian 4 machine I first had to:
- uncomment 'de_DE' in file /etc/locale.gen and afterwards
- run locale-gen from the shell

preg_quote> <preg_match_all
Last updated: Fri, 04 Jul 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites