View Full Version : preg_match syntax
Steveo31
03-08-2004, 07:06 AM
Heyoooo-
From php.net:
<?php
// get host name from URL
preg_match("/^(http:\/\/)?([^\/]+)/i",
"http://www.php.net/index.html", $matches);
$host = $matches[2];
// get last two segments of host name
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>
What on EARTH are all those dashes slashes and carots? I know I will eventually need the preg_match but sheesh... I'm gettin dizzy....
:thumbsup:
Fou-Lu
03-08-2004, 07:44 AM
Ah, matching is great fun!
<?php
// get host name from URL
preg_match("/^(http://)?([^/]+)/i",
"http://www.php.net/index.html", $matches);
$host = $matches[2];
// get last two segments of host name
preg_match("/[^./]+.[^./]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>
^ = start
. = a character
| = or
% = does not have
+ = at least one
? = there may be one
$ = end
[] = a range - from...to
Now, due to the way the VBulletin works, you have obviously had information stripped out as well. Your / blah blah /i indicates case insensitive.
The first set of the search is looking for the [b]posibility of http://[b] and any number of /. Your new $host = www.php.net/index.html.
the second is searching for at least one set of characters and / at the beginning, with one character. Since I'm assuming thats supposed to be \.\/ for the . in there, that becomes a period instead, its searching for the period, not a character.
Voila, you end up with:
domain name is: php.net
Hope that helps you, it does take awhile to get used to it all.
Wait a minute... something seems wrong with that.... should that be www not php.net for the echo out?
Ok, yeah no thats right. I would have done a little different, but assuming the second parts are [^\.\/]+\.[^\.\/]+$ it will work fine.
Steveo31
03-08-2004, 05:01 PM
Excellent... that list of all the symbols was what I was after, as well as the explanation. Fantastico. I was told that ".... is great fun" when I started in Flash with for() loops, so I figured I would get the same response.
What is the forward slash mean?
preg_match("/[^./]+.[^./]+$/",_$host,_$matches);
Fou-Lu
03-09-2004, 02:44 PM
/ would be searching for literal
\ would escape special characters. Like if you wanted to look for something that contained a dollar sign, you need to state it as \$ otherwise it will search for the end of a string.
Its matching it on each foundation of a set of characters divided by a / sign, the php.net/index.php for instance, in there it splits them in two, and returns $matches[0] as php.net.
Also, numbers work a little bit different as well, so we won't get into that... yet...
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.