2010-08-17 14 views
5

Desidero avere un'espressione regolare che assicuri che l'inizio della stringa contenga "http: //" e "/" e la fine.preg_match: assicurarsi che l'inizio e la fine contengano qualcosa

Questa è una versione più lunga che mi è venuta,

if(!preg_match("/(^http:\/\//", $site_http)) 
{ 
$error = true; 
echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link contains http:// at the start."/>'; 
} 
elseif (!preg_match("/\/$/", $site_http)) 
{ 
$error = true; 
echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link has ended with a /."/>'; 
} 

ma ho pensato che queste due espressioni possono mettere insieme come qui di seguito, ma non funzionerà,

if(!preg_match("/(^http:\/\/)&(\/$)/", $site_http)) 
{ 
$error = true; 
echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link contains http:// at the start and a/at the end."/>'; 
} 

le molteplici espressioni che ho provare a combinare deve essere sbagliato! qualche idea?

grazie, Lau

+0

Potete fornire un campione di stringa? – Codex73

risposta

9
if(preg_match('/^http:\/\/.*\/$/', $site_http)) 
{ 
    ... 
} 

Le forze ^http:\/\/http:// nella parte anteriore, il \/$ costringe una barra alla fine, e .* permette tutto (e possibilmente nulla) tra.

Ad esempio:

<?php 

foreach (array("http://site.com.invalid/", "http://") as $site_http) { 
    echo "$site_http - "; 
    if (preg_match('/^http:\/\/.*\/$/', $site_http)) { 
    echo "match\n"; 
    } 
    else { 
    echo "no match\n"; 
    } 
} 
?> 

genera il seguente output:

http://site.com.invalid/ - match 
http:// - no match
+0

esplosione, mi hai battuto. Sta scrivendo quando ha detto una nuova risposta. :) –

+0

grazie mille, gbacon! leggenda! :-)) – laukok

+0

@lauthiamkok Prego! Sono contento che aiuti. –

Problemi correlati