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 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动