1

I Have a Variable which contain following elements

$value= ' ["1","7.9","12\/01\/2015"] ';

Now I want to make a array so, that it will contain following values :-

$array[0] = 7.9;
$array[1] = 12/01/2015;

i want PHP Regex which can able to seprate the following element in the above manner. i tryed

$ans = preg_match('/^[0-9,]+$/', $value);

But this will not work. Plz Help what to do. to get the array with the above manner.

array[0] = 7.9; //amount
array[1]= 12/01/2015; //Date
2
  • 1
    did you want the values inside double quotes? Why you don't want 1 does the amount must have a decimal point? Commented Jul 25, 2014 at 11:22
  • The syntax of $value= " ["1","7.9","12\/01\/2015"] "; looks incorrect. Did you mean to enclose it in single quotes? You could possibly use explode if you want to separate a string by a delimiter Commented Jul 25, 2014 at 11:24

1 Answer 1

3

your value " ["1","7.9","12\/01\/2015"] " seems to me to be a json encoded array, I'd use json_decode to get what you want:

$value = ' ["1","7.9","12\/01\/2015"] ';
$array = json_decode(trim($value));//remove leading and trailing spaces
//or as pointed out to me in the comments
$array = json_decode($value);
//remove first element ($array is now [1, 7.9, 12/01/2015]
$result = array_slice($array, 1);
var_dump($result);//array(7.9, 12/01/2015)

This is assuming the double quotes around the values (1, 7.9 and the date) are properly escaped, because as it stands, $value is not a valid string.

codepad demo

Using regex like /[^\/\.,"]+[\.\/][^"\.,]+/ would work, too, but all in all, that's not to be recommended here. Still, for completeness:

preg_match_all('/[^\/\.,"]+[\.\/][^"\.,]+/', $value, $matches);
$result = $matches[0];
var_dump($result);
Sign up to request clarification or add additional context in comments.

5 Comments

No need to call trim() before json_encode(). Whitespace is allowed in JSON.
Warning: array_slice() expects parameter 1 to be array,
@Sidj: copy pasted on phpfiddle, writecodeonline and codepad, worked fine every time
I am using CURL to capture that $value Data & when using it Its not working.
@Sidj: dump the raw response, because going on what you've posted here, my answer should work...

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.