我想通过preg_replace转换如下

时间:2015-04-05 23:46:11

标签: preg-replace preg-match

我想通过preg_replace转换如下。
我怎么知道答案?

preg_replace($pattern, "$2/$1", "One001Two111Three");

结果>三/ Two111 / One001

2 个答案:

答案 0 :(得分:0)

您最好使用preg_split,它比preg_replace简单得多,它适用于任意数量的元素:

$str = "One001Two111Three";
$res = implode('/', array_reverse(preg_split('/(?<=\d)(?=[A-Z])/', $str)));
echo $res,"\n";

<强>输出:

Three/Two111/One001

正则表达式/(?<=\d)(?=[A-Z])/在数字和大写字母之间的边界上分割,array_reverse颠倒preg_split给出的数组的顺序,然后反向数组的元素由implode连接使用/

答案 1 :(得分:0)

$string = "One001Two111Three";
$result = preg_replace('/^(.*?\d+)(.*?\d+)(.*?)$/im', '$3/$2/$1', $string );
echo $result;

结果: Three/Two111/One001

DEMO

<强>说明

^(.*?\d+)(.*?\d+)(.*?)$
-----------------------

Options: Case insensitive; Exact spacing; Dot doesn't match line breaks; ^$ match at line breaks; Greedy quantifiers; Regex syntax only

Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed) «^»
Match the regex below and capture its match into backreference number 1 «(.*?\d+)»
   Match any single character that is NOT a line break character (line feed) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
   Match a single character that is a “digit” (any decimal number in any Unicode script) «\d+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regex below and capture its match into backreference number 2 «(.*?\d+)»
   Match any single character that is NOT a line break character (line feed) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
   Match a single character that is a “digit” (any decimal number in any Unicode script) «\d+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the regex below and capture its match into backreference number 3 «(.*?)»
   Match any single character that is NOT a line break character (line feed) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) (line feed) «$»

$3/$2/$1

Insert the text that was last matched by capturing group number 3 «$3»
Insert the character “/” literally «/»
Insert the text that was last matched by capturing group number 2 «$2»
Insert the character “/” literally «/»
Insert the text that was last matched by capturing group number 1 «$1»