1

preg_replace() is returning an empty string for the following line of code. The aim is to replace anything that's not a number with a hyphen. Through an online tester I believe the regex catches the right things, but for some reason this line is always returning an empty string.

preg_last_error() returns no error. Any suggestions?

$subRef = preg_replace("/[^(\d)]/g", "-", $subRef);
Chris
  • 5,882
  • 2
  • 32
  • 57
  • 2
    Enable `error_reporting(E_ALL);`. It'll tell you what's wrong with your regex specifier. – mario Aug 29 '13 at 15:34
  • What is the value of subRef? – Kieran Aug 29 '13 at 15:35
  • 4
    possible duplicate of ["Unknown modifier 'g' in..." when using preg\_match in PHP?](http://stackoverflow.com/questions/3578671/unknown-modifier-g-in-when-using-preg-match-in-php) – mario Aug 29 '13 at 15:36
  • Currently testing subRef with 9999-99.99, echoing before and after this line, so pretty sure the right value is going in. – Chris Aug 29 '13 at 15:36
  • as @mario said enable error_reporting as you will be forever having unexplained problems developing with it disabled http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php – Anigel Aug 29 '13 at 15:40
  • @mario - That was my problem, thank you. I presume preg_replace won't accept the g modifier as it is global by default - if you'd like to post that as a full answer, I'll happily accept! – Chris Aug 29 '13 at 15:46

2 Answers2

9

For people finding this on Google, the issue was my g flag.

As I understand, PHP doesn't have a global flag, as the function you use decides if the regex is global or not.

Credit for this answer to Mario in the comments on the question.

Community
  • 1
  • 1
Chris
  • 5,882
  • 2
  • 32
  • 57
5

Try

preg_replace('/\D/', '-', $subRef);

instead. \D is "not-a-digit"

php > $foo = 'abc123def';
php > echo preg_replace('/\D/', '-', $foo);
---123---
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Thanks, wasn't aware of the \D, and it's a much tidier way of doing what I'm doing. It was the g-modifier causing the problem though. Using this regardless however, Cheers! – Chris Aug 29 '13 at 15:48