Reputation: 47648
I'm trying to search-replace through a string that may contain any number of characters preceded by a backslash, and produce the same string but with backslash removed, and those characters surrounded by single quotes.
E.g.:
ab c\d\e fg \h ij
Should produce
ab c'de' fg 'h' ij
Is it possible to do this with a single preg_replace?
Upvotes: 0
Views: 36
Reputation: 89639
You can't do it with preg_replace
(because you have to deal with an unknow number of repetitions), you must use preg_replace_callback
to find all the sequence. Then the callback function removes the backslashes and returns the result between quotes:
$str='ab c\d\e fg \h ij';
echo preg_replace_callback('~(?:\\\.)+~', function ($m) {
return "'". str_replace('\\', '', $m[0]) . "'";
}, $str);
Upvotes: 1