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, 18 Jul 2008

view this page in

preg_match

(PHP 4, PHP 5)

preg_match — Riconoscimento con espressioni regolari

Descrizione

mixed preg_match ( string $criterio , string $testo [, array $&testi_riconosciuti [, int $flags [, int $offset ]]] )

Esegue un riconoscimento nel parametro testo utilizzando l'espressione regolare indicata in criterio .

Se viene fornito il terzo parametro, testi_riconosciuti , questo verrà valorizzato con i risultati della ricerca. In dettaglio $testi_riconosciuti[0] conterrà il testo che si incrocia con l'intero criterio di ricerca, $testi_riconosciuti[1] conterrà il testo che soddisfa il primo criterio posto tra parentesi, $testi_riconosciuti[2] il secondo e così via.

Il parametro flags può assumere i seguenti valori:

PREG_OFFSET_CAPTURE
Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset della stringa. Occorre notare che questo cambia il tipo di valore restituito nell'array, infatti ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP.
Il parametro flags è disponibile a partire dalla versione 4.3.0 di PHP.

Normalemente la ricerca parte dall'inizio della stringa oggetto di ricerca. Con il parametro opzionale offset si può specificare da dove cominciare la ricerca. Equivale a passare substr()($testo, $offset) alla funzione preg_match() al posto del parametro testo. Il parametro offset è disponibile a partire dalla versione 4.3.3 di PHP.

La funzione preg_match() restituisce il numero di volte in cui è avvenuto il riconoscimento del criterio . Questo può essere 0 (nessun riconoscimento) oppure 1 se preg_match() si ferma dopo il primo riconoscimento. In condizioni normali, preg_match_all() continua il riconoscimento fino alla fine del parametro testo . preg_match() restituirà FALSE se si verifica un errore.

Suggerimento

Non utilizzare la funzione preg_match() se si desidera controllare se una stringa è contenuta in un'altra. Piuttosto utilizzare strpos() oppure strstr() che sono più veloci.

Example #1 Ricerca del testo "php"

<?php
// La lettera "i" dopo i delimitatori indica una ricerca case-insensitive
if (preg_match("/php/i""PHP è il linguaggio scelto.")) {
    echo 
"Il riconoscimento è avvenuto.";
} else {
    echo 
"Testo non riconosciuto.";
}
?>

Example #2 Cerca la parola "web"

<?php
// La lettera \b nel criterio indica i limiti della parola. Così verrà riconosciuta solo
// la parola "web" e non parte di una parola più lunga come "webbing" oppure "cobweb"
if (preg_match("/\bweb\b/i""PHP è un linguaggio di programmazione per il web scelto da molti.")) {
    echo 
"Il riconoscimento è avvenuto.";
} else {
    echo 
"Testo non riconosciuto.";
}
if (
preg_match("/\bweb\b/i""PHP è un linguaggio di programmazione installato su molti website")) {
    echo 
"Il riconoscimento è avvenuto.";
} else {
    echo 
"Testo non riconosciuto.";
}
?>

Example #3 Estrapolazione del dominio da un URL

<?php
// come ottenere il nome dell'host da un URL
preg_match("/^(http:\/\/)?([^\/]+)/i",
"http://www.php.net/index.html"$matches);
$NomeHost $matches[2];
// come ottenere gli ultimi due segmenti del nome dell'host
preg_match("/[^\.\/]+\.[^\.\/]+$/",$NomeHost,$matches);
echo 
"Nome del dominio:  {$matches[0]}\n";
?>

L'esempio visualizzerà:

Nome del dominio: php.net

Vedere anche preg_match_all(), preg_replace() e preg_split().



preg_quote> <preg_match_all
Last updated: Fri, 18 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, 18 Jul 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites