0
\$\begingroup\$

Given a string like "abcdbcfbc" , I want all the occurrences of 'b' to be interchanged with their previous character.
The output should be: "bacbdcbfc"

I've come up with a temporary solution:

function punjabi_alternate($string) {
    $len = mb_strlen($string);
    $sploded = array(); 
    while($len-- > 0) {
        $sploded[$len] = mb_substr($string, $len, 1); 
    }
    ksort($sploded);
    $len = mb_strlen($string);
    for ($i=0; $i < $len; $i++) {
        if( strcmp($sploded[$i], "b") == 0){
            $temp = $sploded[$i];
            $sploded[$i] = $sploded[$i-1];
            $sploded[$i-1] = $temp;
        }
    } 
    return join('', $sploded);
}

Here I'm using mb_substr as my string contains unicode characters. The b is just an example. In my production version I'm using this instead of "b"

html_entity_decode("&#x0A3F;")

It is working as expected. I'd appreciate if there could be a cleaner way to do it. Also the strings passed to the function can contain as many as 10,000 - 20,000 characters. So, I'd prefer a preg_replace function with regex to do the same.

\$\endgroup\$
  • \$\begingroup\$ Related Stack Overflow question. It looks like you are asking for a regex-based solution rather than a review of the existing code, so I don't believe that Code Review is the appropriate place to ask this question. \$\endgroup\$ – 200_success Apr 5 '17 at 16:58
  • 1
    \$\begingroup\$ regex based solution was a secondary requirement. I just wanted to optimize the code for usage with large strings. \$\endgroup\$ – JiteshPubreja Apr 5 '17 at 23:22
2
\$\begingroup\$

You want to do a string replacement operation, so use preg_replace(). The key is to use backreferences in the replacement. Also, since you seem to be interested in processing Unicode, be sure to use the u flag for the regex.

If, as you say, 'b' is just an example, then you can make it a default parameter.

function punjabi_alternate($string, $char='b') {
    return preg_replace("/(.)($char)/u", '\2\1', $string);
}
\$\endgroup\$
  • \$\begingroup\$ Thanks a lot. It works. before i was trying the similar expression with . (Dot) and $char in single parenthesis . It was giving me single string containing both elements. It never occured to me to use both characters with different parentheses. \$\endgroup\$ – JiteshPubreja Apr 6 '17 at 8:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.