Reputation: 6042
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);
Upvotes: 1
Views: 5314
Reputation: 6042
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.
Upvotes: 9
Reputation: 360632
Try
preg_replace('/\D/', '-', $subRef);
instead. \D
is "not-a-digit"
php > $foo = 'abc123def';
php > echo preg_replace('/\D/', '-', $foo);
---123---
Upvotes: 5