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


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

$str = '';

$str = '';

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




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);


$str = http_build_query($params);



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 = '';

will be changed into

$str = '';

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


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.