Get the parts of a search string

hypertext
language
programming

Splitting a string into component characters

s
t
r
i
n
g

Splitting a string into matches and their offsets

Array ( [0] => Array ( [0] => hypertext [1] => 0 ) [1] => Array ( [0] => language [1] => 10 ) [2] => Array ( [0] => programming [1] => 19 ) )

Getting the domain name out of a URL

Array ( [0] => http://www.php.net [1] => http:// [2] => www.php.net )
domain name is: php.net

Example of use of preg_match

Match: donut, Homer

Pastry: donut

Variant:

Name: Homer

Check if an IP-v4 address is valid

\n"; } else { echo "$ip_addr is NOT valid
\n"; } } ?>

Repetitions

$p='/-?\d+/';
preg_match($p,'100');
1
preg_match($p,'100.10');
1
preg_match($p,'-100');
1
preg_match($p,'toto');
0
preg_match($p,'toto 50');
1
$p='/-?\d+/';
preg_match($p,'toto 50',$a);
echo $a[0];
preg_match($p,'toto -3050',$b);
echo $b[0]; 
50
-3050

Subexpressions

$patternProf = '/([a-zA-Z]{3}\d{1,2})@bfh.ch/';  
$address = 'bie1@bfh.ch';
preg_match($patternProf,$address,$res);
echo "email=".$res[0];
echo "kuerzel=".$res[1];
email=bie1@bfh.ch
kuerzel=bie1
$log= '192.168.1.10 - - [02/Dec/2010:16:31:22 +0100] "GET /coursAWT/hello.php HTTP/1.1" 200 937 ';
$pattern1='/([\d\.]+) -(.*)- (\[.*\])\s"(GET|POST)/'; 
preg_match($pattern1,$log,$res);
foreach($res as $k => $item){
 echo "\$res[$k] = ".$item."\n";
}
$res[0] = 192.168.1.10 - - [02/Dec/2010:16:31:22 +0100] "GET
$res[1] = 192.168.1.10
$res[2] =
$res[3] = [02/Dec/2010:16:31:22 +0100]
$res[4] = GET