Re: Split problem...

From: Date: Fri, 21 Jul 2000 01:44:11 +0000
Subject: Re: Split problem...
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-7498@lists.php.net to get a copy of this message
At 09:21 AM 7/20/00 , Monte Ohrt wrote:
Rob Curts wrote: on 7/20/00 10:43 AM, Kasper (Swebase Network) at kasper@swebase.com wrote:
Is it possible to split http://www.php.net so i only get php.net and not http://www. ??? So i always just get the two last words??? Med vänlig hälsning Kasper Kristiansson 042-217785, Fax 0703-831214
yes of course: Since a "." is a reserved character for regular expressions, you need to escape it in the split function. <? $v = "http://www.php.net/" $a = split("\.",$v); /* $a[0] will be "http://www" (no dot at the end) */ ?> I think he wants to get "php.net" out of the end of the hostname. A more powerful approach would be to use preg_match(). This example will get the last two parts out of the hostname from any URL.
I think what Rob was trying to imply was that $a[0] contained everything up the the first '.', and so
        $a[1] will = 'php'
and
        $a[2] will = 'net/'
You could then get the last 2 words by, for instance,
        $x = count($a) - 1;
        $what_you_want = $a[$x-1].'.'.$a[$x];
Of course, in this particular example you'll get the trailing slash. For a more general approach, you could do something like (untested):
        $v = "http://www.php.net/";
        function get_domain_part($url, $number_of_levels) {
           $rval = '';
           $url_parts = parse_url($url);
           if (is_array($url_parts) && !empty($url_parts['host'])) {
              $host_parts = explode('.', $url_parts['host']);
              $count = count($host_parts);
              for ($i=$count; $i >= min($count,$number_of_levels); $i--)
                 { $rval = $host_parts[$i-1].'.'.$rval; }
              $rval = substr($rval, 0, -1);
           }
           return $rval;
        }
...of course, this might be total overkill for your purposes. At any rate, the parse_url() function in conjunction with Rob's method might be all you want. See
        http://www.php.net/manual/function.parse-url.php
- steve edberg
<? preg_match("/^(.*)([^\.]+\.[^\.]+)(\/.*)?/U", "http://www.php.net/index.html", $matches); echo "I found: ".$matches[1]."\n"; echo "I found: ".$matches[2]."\n"; echo "I found: ".$matches[3]."\n"; ?> results: I found: http://www. I found: php.net I found: /index.html
+- Obscure computer humor, item 77: -------------------------------------+
| Steve Edberg                           University of California, Davis |
| sbedberg@ucdavis.edu                                     (530)754-9127 |
| http://aesric.ucdavis.edu/                  http://pgfsun.ucdavis.edu/ |
+------------------- How are cats and UNIVAC EXEC-8 similar? Fur. Purr. -+

« previous php.general (#7498) next »