I need to get the number before a static string for example the string would be something like 12/50, the /50 will always be the same but I need to know how to find out the dynamic number before the /50 as it will always be changing??
Find dynamic number before static string
Collapse
X
-
-
The problem is that I'm grabbing a webpage and searching for a certain string like 12/50 and I need to get just the number before the forward slash which is dynamic. So I can't use explode as its not just 12/50, there is everything else thats on the page, if you get me.
Code:$original_file = file_get_contents($page);
Comment
-
Ahh ok. For that you could use a regular expression.
It could be as simple as:
[code=php]<?php
// Fetch the contents of the page
$pageContents = file_get_conten ts("http://example.com");
// Create the regexp pattern
$regexp = '#(\d+)/(\d+)#';
// Find all matches for the regexp
// in the page contents.
if(preg_match_a ll($regexp, $pageContents, $matches))
{
// Print the array of matches.
echo "<pre>", print_r($matche s, true), "</pre>";
}
else
{
echo "Nothing found!";
}
?>[/code]
To explain how the regular expression pattern works, this is how I look at it:- I start with two numbers, which are represented by a the \d characters.
Code:\d\d
- And they should be allowed to be more than one number (a string of numeric characters), so I add the + sign to the character class. The + sign means: "One or more of the preceding character".
Code:\d+\d+
- The I separate them by a forward slash, like in the string you posted.
Code:\d+/\d+
- To allow PHP to fetch each number separately, I enclose them both in parenthesis. They create what is referred to as a "group", which can be used to reference the match both inside and outside the expression. (In our case, we are only concerned about the "outside" part, which allows PHP to read them into an array for us.)
Code:(\d+)/(\d+)
- The whole thing is then enclosed in custom delimiters, as per PHP's PCRE implementation. I chose the # chars, but it can be any char you want.
Code:#(\d+)/(\d+)#
And that's it. When executed as in the code above, PHP might print something like:
Code:Array ( [0] => Array ( [0] => 20/50 [1] => 25/40 [2] => 100/545 ) [1] => Array ( [0] => 20 [1] => 25 [2] => 100 ) [2] => Array ( [0] => 50 [1] => 40 [2] => 545 ) )Comment
- I start with two numbers, which are represented by a the \d characters.
-
Comment
Comment