0

With the use of preg_replace() I want to change string of http://www.vaidehielink.com/ to www.vaidehielink.com.

I have succeeded to get result of www.vaidehielink.com/ with the following code:

$str = "http://www.vaidehielink.com/";
$pattern= '(http://)';
$copy_date = preg_replace($pattern, "", $str);

But I am looking for a pattern to remove the trailing /

2
  • is it not possible with preg_replace() Commented May 19, 2015 at 18:23
  • Regular expressions aren't necessary for this. If you really want to find the host part of a URL, you can use PHP's built-in url_parse function instead of your own code. (Of course, if you're just practicing your regular expressions, then go ahead...) Commented May 19, 2015 at 19:21

2 Answers 2

1

No need for regex.

$copy_date = str_replace(array('http:', '/'), '', $str);

Or probably the proper tool:

$copy_date = parse_url($str, PHP_URL_HOST);
Sign up to request clarification or add additional context in comments.

5 Comments

I first fell for the same. He only wants to delete the slash, when it is at the end.
OK, where did you see that?
so that trailing slash can also be removed. <- here
Yes, in a host name there can't be a /. So it would be part of the path.
You're right, but since OP wrote: i want to change string I didn't made the assumption, that it has to be a valid url. But I think now/that would be up to OP, to clarify if his string is a valid url.
0

Besides, that you are missing delimiters, just change your pattern and your replacement to this:

$pattern= "/^(http:\/\/)(.*?)(\/)?$/";
echo $copy_date = preg_replace($pattern, "$2", $str);

output:

www.vaidehielink.com

Basically your only grab the string between http:// and / if there is one.

7 Comments

can you explain the $pattern= "/^(http:\/\/)(.*?)(\/)?$/";
@abhiAhere ^(http:\/\/) matches http:// at the beginning of the string and (\/)?$ matches / 0 or 1 time at the end of the string; And you just grab the middle part of this, which is (.*?)
@ Rizier123 thanks i was googling for explanation of pattern, but not getting appropriate answer .this answer help me a lot,
@abhiAhere Then I can only recommend you a very useful site: regex101.com <- Just throw/ or test your regex'es in there and to the right you get a really good and detailed explanation
@ Rizier123 thanks again.I will go through the link you suggested
|

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.