Reputation: 6509
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
Reputation: 7005
Is it always the first thing in the string? If so, use intval.
echo intval('4 teams');
Upvotes: 0
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
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