3

How can I extract domain name from string like "AmericanSwan.com Indian Websites" ?

I am tried many options but none of them provide domain name.

5
  • did you used substr()? Commented Jul 18, 2016 at 5:39
  • Do you want just domain name like 'AmericanSwan'? Commented Jul 18, 2016 at 5:39
  • substr() will work if I know string "domain name" which I want to search. Actually I have CSV with more than 1000 rows and each row may have different domain name which is not predefined. Commented Jul 18, 2016 at 5:41
  • you said the source is a csv file. Would you open the file in notepad and print a couple of lines exactly as they appear? It will determine the best solution Commented Jul 18, 2016 at 5:43
  • I already have open file and loop is working. I just wanted to extra domain name from particular column for each row. Commented Jul 18, 2016 at 5:44

2 Answers 2

4

Use below Regular Expression for extracting domain name from string, Try:

$input = 'AmericanSwan.com Indian Websites';
preg_match_all('#[-a-zA-Z0-9@:%_\+.~\#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~\#?&//=]*)?#si', $input, $result);
echo $result[0][0]; //$result will give list of all domain names of string, you can also loop through it

Output:

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

1 Comment

This doesn't work if a URI path is attached to the domain. For example, with input website.com/page.php, it doesn't return just the domain; it also includes the path
0

You should refer to this function: parse_url()

And this example: parse_url example

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.