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.
How can I extract the domain.com from the following string using regular expressions:
domain.com: username
I need the fastest method.
Thanks.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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..... ;-)
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I thought there's a more elegant method. I'm using:
$domain = explode(':', $domain);
$domain = $domain[0];