I want to let the user provide both the pattern and the replace string for the PHP preg_replace function.
This code works for me:
echo preg_replace('/(o)/', ', ${1}h!', 'hello'); // echoes 'hell, oh!'
Case conversion tokens, i.e. \u
, \l
, \U
, \L
and \E
, within the replace string don't work for me though. Here'an example of the code I'm trying to execute:
echo preg_replace('/(o)/', '\u${1}','hello'); // expected to echo 'hellO', echoes 'hell\uo'
Because the replacement string is dynamic, I believe I can't implement this case conversion functionality using callback functions instead of a plain replacement string.
These are the things I tried but to no avail:
echo preg_replace('/(o)/u', '\\u${1}','hello');
/u
making the code look like this. I didn't think that would work, but I've read about that somewhere. Trying didn't hurt:echo preg_replace('/(o)/u', '\u${1}','hello');
The result of the substitution is hell\uo
, even when I executed it on https://sandbox.onlinephpfunctions.com)The current situation is that I'm confused about where my mistake might be:
\u
, \l
, \U
, \L
, \E
in a wrong way@1: I got utterly confused if PCRE2 was suddenly renamed to PCRE at some point and I'm therefore already good to go. I couldn't find anything about installing PCRE2 for PHP under Windows though. I don't mind using a virtual machine with Linux on it if that's the issue. Here's what phpinfo();
tells me about my PCRE:
pcre
PCRE (Perl Compatible Regular Expressions) Support => enabled
PCRE Library Version => 10.34 2019-11-21
PCRE Unicode Version => 12.1.0
PCRE JIT Support => enabled
PCRE JIT Target => x86 64bit (little endian + unaligned)
@2&3: Looking forward to hearing about your corrections
@4: I might be able to execute Perl script through PHP then or some command tool that supports this kind of functionality. Would there be any cool options here?
You can't use function in the replacement, you have to use preg_replace-callback. The code generated by regex101 is wrong.
$res = preg_replace_callback('/(o)/',
function ($m) {
return strtoupper($m[1]);
},
'hello'
);
echo $res;
Output:
hellO