1

I have this string:

a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}

I want to get number between "a:" and ":{" that is "3". I try to user substr and strpos but no success. I'm newbie in regex , write this :

preg_match('/a:(.+?):{/', $v);

But its return me 1. Thanks for any tips.

1
  • 2
    This looks like a serialized PHP array (with a wrong number of elements …?). Why not deserialize it and use count() on the actual array? Commented Nov 20, 2011 at 8:56

5 Answers 5

4

preg_match returns the number of matches, in your case 1 match.

To get the matches themselves, use the third parameter:

$matches = array();
preg_match(/'a:(\d+?):{/', $v, $matches);

That said, I think the string looks like a serialized array which you could deserialize with unserialize and then use count on the actual array (i.e. $a = count(unserialize($v));). Be careful with userprovided serialized strings though …

Sign up to request clarification or add additional context in comments.

Comments

2

If you know that a: is always at the beginning of the string, the easiest way is:

$array = explode( ':', $string, 3 );
$number = $array[1];

Comments

2

You can use sscanfDocs to obtain the number from the string:

# Input:
$str = 'a:3:{i:0;i:2;i:1;i:3;i:2;i:4;}';

# Code:
sscanf($str, 'a:%d:', $number);

# Output:
echo $number; # 3

This is often more simple than using preg_match when you'd like to obtain a specific value from a string that follows a pattern.

Comments

1

preg_match() returns the number of times it finds a match, that's why. you need to add a third param. $matches in which it will store the matches.

Comments

1

You were not too far away with strpos() and substr()

$pos_start = strpos($str,'a:')+2;
$pos_end = strpos($str,':{')-2;
$result = substr($str,$pos_start,$pos_end);

preg_match only checks for appearance, it doesn't return any string.

2 Comments

True, I forgot to make the position of $pos_start +2 (for the 2 characters of a: Now it should be ok.
Not my day, so sorry! Edited it now, tested, works - even with more than one number. Reason for -2 at the end of $pos_end is that you need to decrease the length of 2, when you increased the $pos_start of 2.

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.