Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Spiral's avatar

How can remove some portion of string between two character if exist

I have a string in which I want to remove some portion of string if exist otherwise same which giving

you can see my code

{{host}}/api/profile?first_name=berro&last_name=sin?first_name=berro&last_name=sing

I want to remove this part if exist

?first_name=berro&last_name=sin

I'm using this substr($request->url, 0, strpos($request->url, "?")) but this remove all after ? character I want only remove between if exist

0 likes
12 replies
sr57's avatar

Try with preg_replace

1 like
Spiral's avatar

Thanks, @sr57 for replying to me can you give me an example like this How can remove this ?first_name=berro&last_name=sin from all if exists

sr57's avatar

:-)

 $url=preg_replace('/\?first_name=[^\&]*\&last_name=[^\&]*/', '', $url);

I did not test, you should be able to do to fine tuning, if not ask

Explanation :

\ to escape special character, so to be double in php, but does not show on the code above

[^&] : all char except &

1 like
Spiral's avatar

Ok Brother Thanks.. One more how can put if condition in this if exists then replace otherwise, will original URL

sr57's avatar

No need, $url will be unchanged if no replacement made.

All is here https://regexr.com/ (it could take a while to learn every possibilities)

1 like
Spiral's avatar

Brother, you did not understand my problem I have two special characters ?first_name=berro&last_name=sin? in which want to delete if the value will give in this ? specific character then remove otherwise not The values will give dynamically

sr57's avatar

Your question "How can remove some portion ..."

No s at portion :-)

So it's an other question, so close this one and open a new one ... or just call in a row my example with your 2 filters.

1 like
Spiral's avatar

Thanks, @sr57 for advising me.. Can you put the answer here

Brother, you can check my question that I want to remove some portion of the string between two special characters if exist

sr57's avatar

Yes, your have everything with my answer, but you don't understand, I suggest you to reread my previous anwer to try on different examples.

1 like
abrada's avatar

Well, you can use the PHP parse_str() function. And analyze your URL in the multi-parameter array, then delete the needs parametrs. And to join the string again using the PHP http_build_query() function.

2 likes
Spiral's avatar

Thanks, @jlrdw for replying to me... I want to remove some portion of the string between these special characters ? asdfasdf ? Values will give different every time between these special characters

If will give then remove otherwise not

Please or to participate in this conversation.