I have a string
$name = "name1?name2?name3?name4";
I want to modify this variable as
$name2 = "name1/name2/name3/name4";
using php preg_replace.
How can I do this?
You have to escape the ? with \
<?php
$string = 'name1?name2?';
$pattern = '/\?/';
$replacement = '/';
echo preg_replace($pattern, $replacement, $string);
?>
Time to test...
I stand by my answer, as it answered the OP's question most directly. But my speed comment was not accurate - at all. The differences I found are easy to see, but weren't that impressive IMO.*
The Benchmark: I took the OP's string and concatenated it 500000 times - so each function would have plenty of replacements to do (1.5- or 2-million depending).
Here are the functions and their speeds:
str_replace('?', '/', $test); // name1/name2/name3/name4/
0.388642073
0.389673948
0.385308981
preg_replace('/\?/', '/', $test); // name1/name2/name3/name4/
0.812348127
0.812065840
0.819634199
$bad = array('1?','2?','3?');
$good = array('1/','2/','3/');
str_replace($bad, $good, $test); // name1/name2/name3/name4?
0.712552071
0.725568056
0.718420029
preg_replace('/\?(\w+\d+)/', '/$1', $test); // name1/name2/name3/name4?
1.515372038
1.516302109
1.517566919
So...I lose. This testing showed str_replace() to be 2X faster than preg_replace(). But, 1.5 seconds vs 0.7 seconds (last two functions) isn't bad when you consider all 1.5 million replacements are finished - not to mention the last one will resolve many more combinations than its competitor.
Don't you want the celebratory fist-pump when you write that perfect RegEx function? :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With