9

I'm trying to strip part of a string (which happens to be a url) with Regex. I'm getting better out regex but can't figure out how to tell it that content before or after the string is optional. Here is what I have

$string='http://www.example.com/username?refid=22';
$new_string= preg_replace('/[/?refid=0-9]+/', '', $string);
echo $new_string;

I'm trying to remove the ?refid=22 part to get http://www.example.com/username

Ideas?

EDIT I think I need to use Regex instead of explode becuase sometimes the url looks like http://example.com/profile.php?id=9999&refid=22 In this case I also want to remove the refid but not get id=9999

2 Answers 2

9

parse_url() is good for parsing URLs :)

$string = 'http://www.example.com/username?refid=22';

$url = parse_url($string);

// Ditch the query.
unset($url['query']);

echo array_shift($url) . '://' . implode($url);

CodePad.

Output

http://www.example.com/username

If you only wanted to remove that specific GET param, do this...

parse_str($url['query'], $get);

unset($get['refid']);

$url['query'] = http_build_query($get);

CodePad.

Output

http://example.com/profile.php?id=9999

If you have the extension, you can rebuild the URL with http_build_url().

Otherwise you can make assumptions about username/password/port and build it yourself.

Update

Just for fun, here is the correction for your regular expression.

preg_replace('/\?refid=\d+\z/', '', $string);
  • [] is a character class. You were trying to put a specific order of characters in there.
  • \ is the escape character, not /.
  • \d is a short version of the character class [0-9].
  • I put the last character anchor (\z) there because it appears it will always be at the end of your string. If not, remove it.
Sign up to request clarification or add additional context in comments.

7 Comments

@BandonRandon My code above covers the case where you only want to remove one GET param.
@alex, is that method faster/standard over regex?
@Bandon Regexs are usually slow. Anyway, this method should be easier to read and that's what's important.
@Alex, sorry to be a pain but it seems that URL is being encoded with %3B which is hex for ; CodePad
@Bandon What string are you using for input?
|
4

Dont use regexs if you dont have to

echo current( explode( '?', $string ) );

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.