Jump to content

[SOLVED] reversing chars


b00ker_b0y

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/71511-solved-reversing-chars/
Share on other sites

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'

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)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.