drj26159 2013-12-12 19:06
浏览 33
已采纳

preg_match正确的正则表达式

Since hours i try to find the correct regular expression. Let's say i have this:

$string = 'a=a.split("")';

and

$string = 'a=Ik(a,66)';

What i want to get as output is:

[1] => a
[2] => a
[3] => split
[4] => ""

and for the second one:

[1] => a
[2] => IK
[3] => a,66

I tried:

preg_match('#(.+)=(.+).(.+)[(](.+)[)]#', $string, $matches);

but this outputs:

Array
(
    [0] => a=a.split("")
    [1] => a
    [2] => a.spl
    [3] => t
    [4] => ""
)

Why do i want this? I want to convert some javascript to PHP. For example:

function Hk(a) {
    a = a.split("");
    a = a.slice(1);
    a = a.reverse();
    a = Ik(a, 66);
    a = a.slice(2);
    a = a.reverse();
    a = Ik(a, 12);
    return a.join("")
}

function Ik(a, b) {
    var c = a[0];
    a[0] = a[b % a.length];
    a[b] = c;
    return a
}

# Edit: What i want is to convert it to PHP code and ouput it. I do not want to execute it.

For example the above javascript code should became something like this:

First function:

$a = str_split($a);
$a = array_slice($a, 1);
$a = array_reverse($a);
$a = self::Ik($a,66);
$a = array_slice($a, 2);
$a = array_reverse($a);
$a = self::Ik($a,12);
return implode("", $a);  

second function:

$c = $a[0];
$a[0] = $a[$b%count($a)];
$a[$b] = $c;
return $a;  

The function part itself is not imporant. I need only the logic in the function itself.

  • 写回答

2条回答 默认 最新

  • dongzhang1839 2013-12-12 19:12
    关注

    You might want to consider preg_split:

    $arr = preg_split('/[=()]/', 'a=a.split("")', -1, PREG_SPLIT_NO_EMPTY);
    Array
    (
        [0] => a
        [1] => a.split
        [2] => ""
    )
    
    $arr = preg_split('/[=()]/', 'a=Ik(a,66)', -1, PREG_SPLIT_NO_EMPTY);
    Array
    (
        [0] => a
        [1] => Ik
        [2] => a,66
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据