/    Sign up×
Community /Pin to ProfileBookmark

Two real quick questions about PHP strings

1) Can PHP remove characters from a string? For example, if I had “1,222” or “33,451,450”, could it find and remove the commas?

2) Can PHP count the number of characters in a string?

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@YaroslaFFeb 06.2007 — Sure,

1) http://php.net/manual/en/function.str-replace.php

2) http://php.net/manual/en/function.strlen.php

But if you have Unicode string, you have to use similar functions for multibyte strings (mb_strlen, etc.)
Copy linkTweet thisAlerts:
@bokehFeb 06.2007 — could it find and remove the commas?[/QUOTE]That is a very ill thought-out validation technique. Instead of a blacklist you should have a whitelist of allowed characters. For example if you want to allow only decimal digits you could use the following: [code=php]$digits = preg_replace('/[^d]/', '', $WithCommas); [/code]

Can PHP count the number of characters in a string?[/QUOTE]strlen()
Copy linkTweet thisAlerts:
@Mr_Initial_ManauthorFeb 06.2007 — That is a very ill thought-out validation technique. Instead of a blacklist you should have a whitelist of allowed characters. For example if you want to allow only decimal digits you could use the following: [code=php]$digits = preg_replace('/[^d]/', '', $WithCommas); [/code]
[/QUOTE]


It has nothing to do with validation. It has to do with counting how many digits there are in, say, 1,000.
Copy linkTweet thisAlerts:
@bokehFeb 06.2007 — It has nothing to do with validation. It has to do with counting how many digits there are in, say, 1,000.[/QUOTE]It is still ill-conceived; white-listing is always better. [code=php]<?php

$formated_number = "33,451,450";

$num_digits = strlen(preg_replace('/[^d]/', '', $formated_number));

echo $num_digits;

?>[/code]
×

Success!

Help @Mr_Initial_Man 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 6.2,
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: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

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