3

Having a little issue with RegEx, I have the strings

AM.name:ASC,AMAdvanced.start:DESC,

AMAdvanced.start:DESC,AM.Genre:Action

and need to break them into

array(0){

AM.name => ASC,

AMAdvanced.start => DESC
}

and 

array(0){

AMAdvanced.start => DESC,

AM.Genre => Action

}

Any help would be fantastic since completely new to regex

3
  • I have the strings - where is the bound of strings? Commented Jun 21, 2015 at 14:39
  • I've tried all the solutions to no effect, the strings will be sent via JQuery and managed server side (with PHP) and every solution nests them incorrectly, the strings are separate and not processed at the same time, i need the script compatible with both, this is the best output so far Array ( [0] => Array ( [0] => Array ( [0] => AM.name [1] => ASC ) [1] => Array ( [0] => AMAdvanced.start [1] => DESC ) ) [1] => Array ( [0] => Array ( [0] => AMAdvanced.start [1] => DESC ) [1] => Array ( [0] => AM.Genre [1] => Action ) ) ) Commented Jun 21, 2015 at 16:07
  • does it 4 strings? 2 string? 3 strings (one is empty)? Commented Jun 21, 2015 at 16:18

3 Answers 3

2

No need of regex here.

Steps:

  1. explode by comma ,
  2. Loop over exploded array
  3. Explode by colon :
  4. Push into new array

Code:

$newArr = array();
foreach (explode(',', trim($str, " ,")) AS $el) {
    $el = explode(':', $el);
    $newArr[$el[0]] = $el[1];
}
print_r($newArr);
Sign up to request clarification or add additional context in comments.

Comments

0

This will create a single array with the entries

<?php
$dir = array();
$strArray = array('AM.name:ASC,AMAdvanced.start:DESC','AMAdvanced.start:DESC,AM.Genre:Action');
foreach ($strArray as $i => $str) {
    $el = explode(',', $str);
    foreach ($el as $e) {
        $dir[$i][] = explode(':',$e);
    }
}
print_r($dir);

Comments

0

You can first split your text with new line character :

 var arr = data.split('\n');

then loop over your array and use str.replace method for your items :

var i;
for (i = 0; i < arr.length; ++i) {

 alert(arr[i].replace(/(\w+):(\w+)/g, '$1=>$2'));

}

You can also split the result for each item with , :

var i;
for (i = 0; i < arr.length; ++i) {

 var temp=arr[i].replace(/(\w+):(\w+)/g, '$1=>$2');
 alert(temp.split(','));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.