michaelmcgurk
michaelmcgurk

Reputation: 6509

Retrieve an integer from a piece of text with PHP

Can someone explain how I strip a string of a particular integer?

My string is: 4 Teams

So wherever it finds the word 'Teams', I'd like to pull out the integer before this.

Is this possible and how would I achieve this?

Many thanks :)

Upvotes: 1

Views: 65

Answers (3)

Jessica
Jessica

Reputation: 7005

Is it always the first thing in the string? If so, use intval.

echo intval('4 teams');

Upvotes: 0

alexis
alexis

Reputation: 50200

wherever it finds the word 'Teams', I'd like to pull out the integer before this.

This regex does exactly as you say:

'(\d+)\s+Teams'

Use it like this:

$mytext = "I have 3 Teams, then 4 Teams, then only 3 Teams";
preg_match_all('/(\d+)\s+Teams/', $mytext, $matches);
$teams = $matches[1];

$mathes[1] contains everything matched by the first (and only) parenthesized group, so $teams should be the array [3, 4, 3].

PS. Hamza had already proposed the right regexp... and thanks for fixing my code!

Upvotes: 4

adaam
adaam

Reputation: 3706

Here you go:

    $str = 'blah blah blah 12'
    preg_match_all('!\d+!', $str, $integers);
    print_r($integers);

preg_match_all is perfect for this.

Upvotes: 1

Related Questions