Jump to content

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)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.