0

Given the string "hello-there-world" I want to use the PHP function preg_replace_callback to change the letters after hyphens with their upper cases: "hello-There-World".

To do this I came up with the following code:

<?php
$str = preg_replace_callback('-([a-z])', 
  function ($matches) 
  {
    return strtoupper($matches[0]);
  }, 
  "hello-there-world");
echo $str;
?>

Nonetheless, the above snippet doesn't work and throws this message:

PHP Warning: preg_replace_callback(): Unknown modifier 'z' in /file.php on line 7

However, if I add the character "~" at the beginning and end of the regex, i.e. '~-([a-z])~', it works fine. Why is that?

I searched info about what this "~" is used for over the internet but found nothing relevant. Can someone tell me what is this character used for in regex and if this is something that happens only in PHP or it's something related to regex per se (meaning it happens cross-languages.) Also please include in the explanation why my code doesn't work without those characters "~".

andres_v
  • 399
  • 1
  • 4
  • 12
  • So "~" turns out to be another way to delimit the regex. However, if I change the regex for this other one with no slash or "~" delimiters: (^[a-z]|-([a-z])), it works. So brackets work like delimiters as well. Thanks for pointing me in the right direction to clarify this. – andres_v Apr 29 '20 at 17:48
  • "A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character." https://www.php.net/manual/en/regexp.reference.delimiters.php – Sammitch Apr 29 '20 at 19:17

0 Answers0