Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove part of a string with regex

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

like image 458
Brooke. Avatar asked Apr 19 '11 04:04

Brooke.


People also ask

How do I remove a specific character from a string in regex?

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]+", "")

How do you trim a word in regex?

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.

What does \+ mean in regex?

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 "(" .


2 Answers

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.
like image 136
alex Avatar answered Oct 13 '22 03:10

alex


Dont use regexs if you dont have to

echo current( explode( '?', $string ) );
like image 34
Galen Avatar answered Oct 13 '22 03:10

Galen