-1

I have a cms that on the front-end grabs pages by id, as shown here:

$pageid = ereg_replace("[^0-9]", "", $_GET['pid']);

This is some old code I am trying to update since POSIX is deprecated, however my efforts to convert (using preg_replace) have been unsuccessful. If anyone could convert that line for me, I would greatly appreciate it.

Add code from comments

My first guess was something along the lines of

$pageid = preg_replace("/[^0-9]/","",$_GET['pid']; 

Which gave errors, so I further reduced it to

$pageid = preg_replace("/^0-9/","",$_GET['pid'] 

Forgive me, my understanding of regex is rather limited.

Toto
  • 89,455
  • 62
  • 89
  • 125
  • 2
    Show us what you've tried – John Conde May 21 '13 at 21:07
  • @john-conde My first guess was something along the lines of $pageid = preg_replace("/[^0-9]/","",$_GET['pid']; Which gave errors, so I further reduced it to $pageid = preg_replace("/^0-9/","",$_GET['pid'] Forgive me, my understanding of regex is rather limited. Thank you. – user2407067 May 21 '13 at 21:12
  • 2
    What error have you got? Your first attempt seems correct except a missing closing parens. – Toto May 22 '13 at 08:07

1 Answers1

2

Let's explain what the posix pattern does.

[^0-9]

[ is the start of a character class and ] is the end. When the character class starts with a ^ it means it's inverted (= matches everything but what is listed). 0-9 is all digits.

So globally [^0-9] matches everything which is NOT a digit.

The same pattern is also available in PCRE so this will work:

$page_id = preg_replace('/[^0-9]/', '', $_GET['pid']);

PCRE has some nice shortcuts to express things. For example [0-9] can be replaced with \d (d stands for digits) Also \D (using a capital letter) is the inverse and thus equivalent to [^0-9].

Which leads to the following:

$page_id = preg_replace('/\D/', '', $_GET['pid']);
hd1
  • 33,938
  • 5
  • 80
  • 91
Savageman
  • 9,257
  • 6
  • 40
  • 50