Link to home
Start Free TrialLog in
Avatar of everactive
everactive

asked on

Extract a value using reg expr

Hello,

How can I extract the domain.com from the following string using regular expressions:

domain.com: username

I need the fastest method.

Thanks.
SOLUTION
Avatar of Beverley Portlock
Beverley Portlock
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of everactive
everactive

ASKER

Hi,

I thought there's a more elegant method. I'm using:

                              $domain = explode(':', $domain);
                              $domain = $domain[0];

I guess it depends on complexity. The requested extraction is a simple enough one, but it has pitalls. For instance a colon is a valid URL chararcter because it separates port numbers. You could have

domain.com:8080: username

In that case a regex would be more flexible, but regexes to carry a performance overhead although in normal use you will never notice it.
And what if

http://domain.com: username

slipped through? The explode method would fail but altering the regex like so would always succeed


     $pattern = '!(http://)?([^:]+):.*!';
     preg_match( $pattern, $test, $arr );

     echo "the domain is " . $arr[2];


Horses for courses I guess.....  ;-)
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial