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);
6
  • 2
    Enable error_reporting(E_ALL);. It'll tell you what's wrong with your regex specifier. Commented Aug 29, 2013 at 15:34
  • What is the value of subRef? Commented Aug 29, 2013 at 15:35
  • 4
    possible duplicate of "Unknown modifier 'g' in..." when using preg_match in PHP? Commented Aug 29, 2013 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. Commented Aug 29, 2013 at 15:36
  • as @mario said enable error_reporting as you will be forever having unexplained problems developing with it disabled stackoverflow.com/questions/845021/… Commented Aug 29, 2013 at 15:40

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

5

Try

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

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

php > $foo = 'abc123def';
php > echo preg_replace('/\D/', '-', $foo);
---123---

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.