0

How can I extract 4 from this string?

$string = "Rank_1:1:4";

I'm trying to get pagerank from Googles server, and the last value (4) is the actual pagerank.

1

3 Answers 3

6

Try

$string = "Rank_1:1:4";
$data = explode(':',$string);
echo end($data);

EDIT

as per @MichaelHampton, if they add more fields later, then use as below

$string = "Rank_1:1:4";
$data = explode(':',$string);
echo $data[2];
Sign up to request clarification or add additional context in comments.

Comments

2

PHP has so many string function you can use ...

Variables

$find = ":";
$string = "Rank_1:1:4";

Using substr

echo substr($string, strrpos($string, $find) + 1);

Using strrchr

echo ltrim(strrchr($string, $find),$find);

5 Comments

This will break when the field is two digits long (and it can be).
@Michael Hampton the OP said rand .. ranking is 0 - 5 stars
@Baba Valid values for PageRank are integers from 0-10 inclusive.
@Michael Hampton, this is a mixed blessing. @Baba answered to Extracting part of a string? which in this case is the correct answer.
You guys are splitting hairs here but who cares. I hope the OP got the answer he/she was looking for already.
0
$pattern = '/:\d+$/';
preg_match($pattern, $string, $matches);
$rank = substr($matches[0],1);

5 Comments

This is too complicated. It may work today, but it's difficult to understand, and it would break if there was ever an extra field.
Michael I respectfully disagree. He asked for the last value and this will always provide that, and is easy to understand for anyone who knows regex.
Sure, this will always give you the last value. Using regex, though, is still more complicated than it needs to be. And, the last value may not be what is actually needed, especially if the input changes later.
Well by that token the second value also may not be what is needed if the input changes later. The OP asked for the last value after the colon and this is a simple way to get it.
There's a subtle but important difference between what someone asked for and what they really need.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.