/    Sign up×
Community /Pin to ProfileBookmark

Remove parts of value

Hi, Im having difficulty figuring this one out.

Im pulling values from a database, the values are numbers prefixed with a letter and an underscore. (eg: t_200)

How do I strip the value down to just the number?

Thanks in advance.

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@NogDogApr 27.2009 — One way would be to simply replace anything that's not a number with nothing:
[code=php]
$numbersOnly = preg_replace('#[^0-9]#', '', $valueFromDB);
[/code]

Another way would be to locate the underscore and take everything after it:
[code=php]
$numbersOnly = substr($valueFromDB, strpos($valueFromDB, '_') + 1);
[/code]
Copy linkTweet thisAlerts:
@DistantUKauthorApr 27.2009 — Thank you, the first worked a treat... I am somewhat curious to why the 0-9 bit does not include the numbers?
Copy linkTweet thisAlerts:
@NogDogApr 27.2009 — If a character class (the stuff within square brackets) starts with a "^", that means to match on anything that does [b][i]not[/i][/b] match that character class (sort of like the PHP "!" negation operator).
Copy linkTweet thisAlerts:
@CharlesApr 27.2009 — It's likely that you are, just a wee bit, better off using "D" instead of "[^0-9]". They mean the same but one takes less typing. However, regular expressions take enough overhead that they are best avoided when possible. The second above is a better solution.
Copy linkTweet thisAlerts:
@NogDogApr 27.2009 — For the record, there is, in fact, a slight difference between "D" and "[^0-9]", though it likely would not matter for this application:
[code=php]
<?php
$str = '';
for($i=1; $i<=255; $i++)
{
$str .= chr($i);
}
echo preg_replace('#D#', '', $str);
?>
[/code]

Output:

[b]0123456789&#178;&#179;&#185;[/b]
×

Success!

Help @DistantUK spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.5,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...