dr3ex Posted February 10, 2013 Share Posted February 10, 2013 I'm having hard time with PREG_REPLACE. I have this string ($str): test \"first string\" test \"second string longer\" end I need to have: %test%first string%test%second string longer%end% This doesn't work: echo preg_replace('#(")(.*?)(")#i', '%$2%', stripslashes($str)); Result: test %first string% test %second string longer% end Thanks all for help! Link to comment https://forums.phpfreaks.com/topic/274292-change-a-string-with-preg_replace/ Share on other sites More sharing options...
Christian F. Posted February 10, 2013 Share Posted February 10, 2013 What you want to match is a quote, which is either followed by or following a space. Since I assume that he order and number of matching characters isn't significant (other than being at least 2), this can be done quite simple: $RegExp = '#[" ]{2,}(\w+)[" ]{2,0}#'; $str = preg_replace ($RegExp, '%$1%', $str); This would match two or more of any combination of spaces and quotes, followed by a a "word" consisting of one or more characters (captured), followed by the first combination. As for the stripslashes (): You should never need to use this in your code, as it is an indicator of something being either unnecessary escaped or doubly-escaped. Make sure that "magic_quotes" is turned off, and that you're not using any functions that adds slashes before this point. Link to comment https://forums.phpfreaks.com/topic/274292-change-a-string-with-preg_replace/#findComment-1411529 Share on other sites More sharing options...
dr3ex Posted February 10, 2013 Author Share Posted February 10, 2013 Thank you, but it doesn't work: $str = 'test "first string" test "second string longer" end'; $RegExp = '#[" ]{2,}(\w+)[" ]{2,0}#'; $str = preg_replace($RegExp, '%$1%', $str); // Error line echo $str; Warning: preg_replace() [function.preg-replace]: Compilation failed: numbers out of order in {} quantifier at offset 21 in C:\...\script.php on line Error line Link to comment https://forums.phpfreaks.com/topic/274292-change-a-string-with-preg_replace/#findComment-1411542 Share on other sites More sharing options...
Christian F. Posted February 10, 2013 Share Posted February 10, 2013 Sorry, added a 0 that shouldn't have been there. Just remove it, and it'll be OK. Link to comment https://forums.phpfreaks.com/topic/274292-change-a-string-with-preg_replace/#findComment-1411548 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.