0

I'm trying to strip all non-number, non-word characters from a string (except hyphens) to create a URI stub. I have the following code:

$urlPrefix = strtolower($this->urlPrefix.(substr($this->urlPrefix, -1) == '-' ? '' : '-'));
$urlPrefix = preg_replace('#\s+#', '-', $urlPrefix);
var_dump($urlPrefix);
$urlPrefix = preg_replace('#[^\d\w\s-]#g', '', $urlPrefix);
var_dump($urlPrefix); exit;

If I set $this->urlPrefix = "Test replace$%^*"; then the first var_dump($urlPrefix) outputs test-replace$%^*- as expected, but the second dump is outputting NULL, but I can't see anything wrong with my regexp, can someone please help me? Why is preg_replace erroring?

Styphon
  • 10,304
  • 9
  • 52
  • 86
  • 4
    `/g` is not a valid regex flag for PCRE. Enable `error_reporting`. – mario Apr 09 '15 at 09:28
  • I do have `error_reporting` enabled, it's forced on as it's a development server. Not sure why it didn't show that error though. – Styphon Apr 09 '15 at 09:31
  • Then it's perhaps `display_errors` that somehow got disabled. As last resort you can often try `set_error_handler("var_dump");` temporarily. – mario Apr 09 '15 at 10:08
  • If `null` is returned use use `preg_last_error_msg()` to get the regex error. – bpile Oct 29 '21 at 13:50

1 Answers1

1

g cannot be used with preg_replace. Here, this sample code works alright:

<?php
   $urlPrefix = "test-replace$%^*-";
   $urlPrefix = strtolower($urlPrefix.(substr($urlPrefix, -1) == '-' ? '' : '-'));
   $urlPrefix = preg_replace('#\s+#', '-', $urlPrefix);
   var_dump($urlPrefix);
   $urlPrefix = preg_replace('#[^\d\w\s-]#', '', $urlPrefix);
   var_dump($urlPrefix);
   exit;
?>

Output:

string(17) "test-replace$%^*-"                                                                                                                                                                                                                         
string(13) "test-replace-"
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • What do you mean by `g cannot be used with preg_replace` statement? PHP by default will do a global match, so we don't need to put the `g` modifier explicitly. It's isn't related to `preg_replace`. – Avinash Raj Apr 09 '15 at 09:54
  • @AvinashRaj: that is exactly what I meant. It is not necessary there, and will cause a warning. – Wiktor Stribiżew Apr 09 '15 at 10:04
  • `g cannot be used with preg_replace` makes me to think like `preg_replace` function is the one which won't allow `g` modifier wher the other func like `preg_match` or `preg_match_all` would allow. – Avinash Raj Apr 09 '15 at 10:07