0

Ex: Found: 84 Displaying: 1 - 84

I want to get out the number 84 between Found and Displaying with preg_match but I'm very bad at regular expression.

Do you know what good tutorial to learn regular expression? I can't find a good one on Google.

Edit inserted from comments below:

I just simplify my problem here. The real problem that I will find it in a full HTML page such as google search. You know what i mean right?

2

2 Answers 2

3

If your input will always be in the same format, there's no need to use regular expressions. Instead, just split the string on spaces:

// explode() on spaces, returning at most 2 array elements.
$parts = explode(" ", "Found: 84 Displaying: 1 - 84", 2);
echo $parts[1];

Update If you really really really want to use preg_match() for this, here's how. This is not recommended for an application this simple though.

// Array will hold matched results
$matches = array();

$input = "Found: 84 Displaying: 1 - 84";

// Your regex will match the pattern ([0-9]+) (one or more digits, between Found and Displaying
$result = preg_match("/^Found: ([0-9]+) Displaying/", $input, $matches);

// See what's inside your $matches array
print_r($matches);

// The number you want should be in $matches[1], the first subgroup captured
echo $matches[1];
Sign up to request clarification or add additional context in comments.

7 Comments

Off topic: I feel a lot of the "regex" questions could be adequately answered by splitting and finding the result.
great idea but i still want to know how to use preg_match too :-) Thanks.
@JaredFarrish If I had a dollar for every time I answered explode() to a regex question... (I do have 10-20 rep for each, but it's not the same :) )
@Michael is correct that if the input is always the same you don't need to do the overhead of using preg_match(). Heck you could also use trim(substr($str, 6, 4)) if the number is between 10 and 999.
@Quy Ok, see above. I've given you enough rope to hang yourself :)
|
1

Fairly simple regex, I included PHP code that uses it:

<?php
preg_match("/(\d+)/", "Found: 84 Displaying: 1 - 84", $matches);
//$matches[0] should have the first number, i.e. 84
echo $matches[0]; // outputs "84"
?>

http://www.regular-expressions.info/ has some pretty good information about how to write regular expressions.

Edit: as mentioned, regular expressions are overkill in this case, tokenizing works fine.

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.