Re-ordering Strings in PHP

时间:2016-04-04 16:36:37

标签: php regex replace

I have a document full of hex colours, as shown below.

#123 is a nice colour but #321 is also fine. However, #fe4918 isn't a bad either.

I'd like to rotate them round, so that #123 would become #231, effectively changing the colour scheme. #fe4918 would become #4918fe.

I know that with regular expressions, one can select the the hash tags but not much else.

4 个答案:

答案 0 :(得分:3)

You could use a regex to do it...

preg_replace('/#([\da-f])([\da-f])([\da-f])(?:([\da-f])([\da-f])([\da-f]))?/i', '#$2$5$3$6$1$4', $str)

CodePad

It works by matching case insensitive hexadecimal numbers 3 or 6 times, and then reverses them using the matched groups.

Alternatively you could match it with a simple regex and callback with preg_replace_callback() and use strrev(), but I think the above example is clear enough.

答案 1 :(得分:1)

You can use a combination of a regex and strrev():

#([a-f0-9]+)

In PHP this would be:

<?php
$string = "#123 is a nice colour but #321 is also fine. However, #fe4918 isn't a bad either.";
$regex = '~#([a-f0-9]+)~';

$string = preg_replace_callback(
    $regex, 
    function($match) {
        return '#'.strrev($match[1]);
    },
    $string
);
echo $string;
// #321 is a nice colour but #123 is also fine. However, #8194ef isn't a bad either.
?>

You can do this in regex alone, but the above logic seems very clear (and maintainable in a few months as well).
See a demo on ideone.com.

答案 2 :(得分:1)

You can use the following to match:

#([\da-f]{2})([\da-f]{2})([\da-f]{2})|#(\d)(\d)(\d)

And replace with:

#\2\5\3\4\1\6

See RegEX DEMO

答案 3 :(得分:1)

您可以使用分支重置组来处理具有相同捕获组编号的两种情况:

$str = preg_replace('~#(?|([a-f\d]{2})([a-f\d]{4})|([a-f\d])([a-f\d]{2}))~i',
                    '#$2$1', $str);