Jump to content

preg_replace with option to exclude some matches


boby

Recommended Posts

Hello guys,

I am looking for a simple way to replace some paging links on a script, but I have a problem that sometimes the regex matches more than I need.
Basically, I need to replace/remove all page 1 links, but it removes also pages starting with 1, for example page 11, 12, 13, 115, etc.

I also don't know, if the paging variables are passed via URL with "[color=red]?[/color]" or "[color=red]&[/color]" or escaped as "[color=red]&a[i]m[/i]p;[/color]"

I am using this code:
[code=PHP]<?php
  preg_replace (array ('#?p=1#i', '#&p=1#i', '#&amp;p=1#i'), '', $source);
?>[/code]

My question is now, how to write te regexp to not include for matching if another numeric value is after the "1" because it now removes also ?p=12 or &p=13 and I don't want that. Can it be done without adding to the regexp all possibilities like line end after 1, or another "&" and then replace the &p=1& with &?
I know this should be done in the paging function, but I don't want to alter the plugin because some are using it as is and not all will have this page 1 removed.

Thank you very much.
Something like this is (I think) what you're looking for.
[code]preg_replace('/(?:\?|&)p=1(?!\d)/', '', $source);[/code]
This will only match 'p=1' if it is not followed by another digit, as in 'p=14', which wont match. I don't think that they're html encoded. You shouldn't need the &amp;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.