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.
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
)
With php PCRE this should work for both patterns, even if you have different array elements filled, depending which pattern matches. I guess you can figure it our with testing the elements for nil etc. This is done with an assertion and lookahead (do we have a dot, which results in one element more):
([^=]+)=(?(?=.+\.)([^.]+)\.([^.]+)|([^.]+))\((.+)\)
This is what comes up:
(
[0] => Array
(
[0] => a=Ik(a,66)
)
[1] => Array
(
[0] => a
)
[2] => Array
(
[0] =>
)
[3] => Array
(
[0] =>
)
[4] => Array
(
[0] => Ik
)
[5] => Array
(
[0] => a,66
)
)
and this one:
(
[0] => Array
(
[0] => a=a.split("")
)
[1] => Array
(
[0] => a
)
[2] => Array
(
[0] => a
)
[3] => Array
(
[0] => split
)
[4] => Array
(
[0] =>
)
[5] => Array
(
[0] => ""
)
)
Hope this is of help ;)