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 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示