regex - regular expression to remove ID=1234 from a string (PHP)

748

I am trying to create a regular expression to do the following (within a preg_replace)

$str = 'http://www.site.com&ID=1620';

$str = 'http://www.site.com';

How would I write a preg_replace to simply remove the &ID=1620 from the string (taking into account the ID could be variable string length

thanks in advance

645

Answer

Solution:

You could use...

$str = preg_replace('/[?&;]ID=\d+/', '', $str);

I'm assuming this is meant to be a normal URL, hence the[?&;]. If that's the case, the& should be a?.

If it's part of a larger list of GET params, you are probably better off using...

parse_str($str, $params);

unset($params['ID']);

$str = http_build_query($params);
910

Answer

Solution:

I'm guessing that& is not allowed as a character in theID attribute. In that case, you can use

$result = preg_replace('/&ID=[^&]+/', '', $subject);

or (possibly better, thanks to PaulP.R.O.):

$result = preg_replace('/[?&]ID=[^&]+/', '', $subject);

This will remove&ID= (the second version would also remove?ID=) plus any amount of characters that follow until the next& or end of string. This approach makes sure that any following attributes will be left alone:

$str = 'http://www.site.com?spam=eggs&ID=1620&foo=bar';

will be changed into

$str = 'http://www.site.com?spam=eggs&foo=bar';

People are also looking for solutions to the problem: mysql - How to create a custom function properly in PHP?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.