0
   $domain_parts = explode('.', preg_replace('/\s+/', '', $_GET['domain']));
   $sld = $domain_parts[0];

I am wanting to do the functionality of lines 1 and 2 into 1 line of code.

An example of what $_GET['domain'] provides is google.com

What is the cleanest way to do this in one line.

2
  • 1
    What's the obsession with fitting the most functionality onto one line? Commented Aug 3, 2013 at 7:01
  • 2
    Or you could always install php 5.4 and just write explode(...)[0]. Commented Aug 3, 2013 at 7:12

3 Answers 3

2

You can try with list like

list($domain_parts) = explode('.', preg_replace('/\s+/', '', $_GET['domain']));

It will directly returns the $domain_parts[0].You can also try with strtok like

echo strtok(preg_replace('/\s+/', '', $_GET['domain']),  '.');

See this STRTOK

Sign up to request clarification or add additional context in comments.

Comments

0

You can also do it without regular expression like this

$sld = str_replace(' ','',substr($_GET['domain'],0,strpos($_GET['domain'],'.')));

1 Comment

Yes. preg_replace needs lot of resource. and is not for replacing just a space. If you don't need the power of regular expressions don't use preg_ functions.
0
list($domain_parts) = explode('.', preg_replace('/\s+/', '', $_GET['domain']));

$domain_parts will contain the first element of the array.

You could get the second element like this:-

list(,$domain_parts) = explode('.', preg_replace('/\s+/', '', $_GET['domain']));

See list() for more details.

Or you could do this:-

$domain_parts = explode('.', preg_replace('/\s+/', '', $_GET['domain']))[0];

if you have PHP >= 5.4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.