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
If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")
You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .
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.
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.
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.
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]
.\z
) there because it appears it will always be at the end of your string. If not, remove it.Dont use regexs if you dont have to
echo current( explode( '?', $string ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With