Home php Delete part of the string via preg_replace

Delete part of the string via preg_replace

Author

Date

Category

There is a string:

$ str = 'http: //site.ru/view? Page = 1 & amp; Cat = 2';

Do you need to remove ? Page = 1 , only instead of the number 1 may be another number. I tried it, did not come out:

$ str = preg_replace ("? Page = [0-9]", '', $ STR);

Answer 1, Authority 100%

answer to your question

$ str = preg_replace ('/ \? Page = [0-9] + /', '', $ STR) ;

In order to remove the URL parameter need another regular

$ str = preg_replace ('/' / '[0-9] + & amp; /', '', $ str );

For testing Regulators, it is convenient to use online services, for example http://regexr.com/


Answer 2, Authority 150%

My option.

$ str = preg_replace ('/(( (? (?!.*& AMP;)) * Page = \ D + & amp; *) / ',' ', $ STR);

Removes the question mark before Page = N , if they do not follow the ampersand.

If the ampersand follows Page = N , the question mark remains, and the ampersand is removed.

for

http://site.ru/view?page=1& ;cat=2
http://site.ru/view?page=1

Get

http://site.ru/view?cat=2
http://site.ru/view

Example of work https://regex101.com/r/fo4uo3/1

UPD

More accurate regular expression https://regex101.com/r/fo4uo3/2

$ str = preg_replace ('' / ((\? | & amp;) (?! * & amp;)) * (? & lt; = \? | & amp;) Page = \ D + & amp; *) / i ',' ', $ ST);

for

http://site.ru/view?cat=2& ;page=1
http://site.ru/view?page=1
http://site.ru/view?page=1& ;cat=2.
http://site.ru/view?nopage=1& ;cat=2.

Get

http://site.ru/view?cat=2
http://site.ru/view
http://site.ru/View?cat=2.
http://site.ru/view?nopage=1& ;cat=2.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions