Delete regex part of string

I am trying to cut part of a string (which is a url) using Regex. I am improving the regex, but can't figure out how to say that the content before or after the line is optional. That's what i

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

I'm trying to remove a part ?refid=22to gethttp://www.example.com/username

Ideas?

EDIT I think I need to use Regex instead of exploding, because sometimes the URL looks like http://example.com/profile.php?id=9999&refid=22In this case, I also want to delete refid, but not getid=9999

+5
source share
2 answers

parse_url() suitable 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

GET, ...

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

unset($get['refid']);

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

CodePad.

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

, URL- http_build_url().

// .

Update

, .

preg_replace('/\?refid=\d+\z/', '', $string);
  • [] - . .
  • \ - escape-, /.
  • \d - [0-9].
  • (\z) , . , .
+7

,

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

All Articles