b00ker_b0y Posted October 2, 2007 Share Posted October 2, 2007 hey, is there a way to reverse only 2 charcters in a string? i know you can reverse an entire string by just using strrev, but was wondering if you could just reverse say 2 letters of the string at a given position i.e. hello and then get... hlelo by some how reversing 2 chars at the 2nd char? Quote Link to comment https://forums.phpfreaks.com/topic/71511-solved-reversing-chars/ Share on other sites More sharing options...
Rithiur Posted October 2, 2007 Share Posted October 2, 2007 There are many solutions to this. You could use, for example, regex like $n = 1; // Position in string $string = preg_replace("/^(.{{$n}})(.)(.)/", '$1$3$2', 'hello'); Or split the string like: $string = 'hello'; $n = 2; // nth character to reverse with the following $string = substr($string, 0, $n - 1) . substr($string, $n, 1) . substr($string, $n - 1, 1) . substr($string, $n + 1); In both cases $string will be 'hlelo' Quote Link to comment https://forums.phpfreaks.com/topic/71511-solved-reversing-chars/#findComment-359991 Share on other sites More sharing options...
MadTechie Posted October 2, 2007 Share Posted October 2, 2007 shouldn't the RegEx be this $string = "Hello"; $n=2; $string = preg_replace('/^(.{0,$n})(.)(.)(.*)/', '\1\3\2\4', $string ); EDIT: added $n Quote Link to comment https://forums.phpfreaks.com/topic/71511-solved-reversing-chars/#findComment-359993 Share on other sites More sharing options...
b00ker_b0y Posted October 2, 2007 Author Share Posted October 2, 2007 cheers for your help people, all sorted. Quote Link to comment https://forums.phpfreaks.com/topic/71511-solved-reversing-chars/#findComment-359998 Share on other sites More sharing options...
Rithiur Posted October 2, 2007 Share Posted October 2, 2007 shouldn't the RegEx be this No, because your regex will accept any number of characters from the beginning between 0 and $n. To switch the position of exactly nth character you must have exactly n - 1 characters before it . Also, there is no need for the fourth subpattern, since there is no need to touch the characters that appear after the switched characters. (Also, the single quotes in your pattern need to be replaced with double quotes for the $n to actually work, but I assume that's just a typo) Quote Link to comment https://forums.phpfreaks.com/topic/71511-solved-reversing-chars/#findComment-360012 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.