regex - How can I remove last comma and all spaces from string, then sanitize it using PHP?
Get the solution ↓↓↓I want to get the string from input field, then format and sanitize it.
The strings I want to get is natural number separated by commas without any spaces. First I want to remove all spaces and last comma. I mean if the formatted string is not match what I want, I want it to return empty string.
//OK examples(without any spaces)
1,2,123,45,7
132,1,555,678
//NG examples
aaa,111,2365
1,2,123,45,7,
-1,2,123,45,7,,,
1, 2, 123, 45, 7
First I want to remove spaces and last comma 1, 235, 146, => 1,235,146
I tried code below
$input = str_replace(' ', '', $input);
rtrim($input, ',');
if (preg_match('/^\d(?:,\d+)*$/', $input)) {
return $input;
}
return '';
This one, if the string has spaces after last comma, it returns empty string.
1,2,123,45,7, => //returns empty string.
I want to format this to '1,2,123,45,7'.
Sorry for my messy explanation...
Answer
Solution:
Replace spaces and trim commas and spaces at beginning or end:
$result = str_replace(' ', '', trim($string, ', '));
Or:
$result = trim(str_replace(' ', '', $string), ',');
Then if you only want numbers and commas (no letters etc.) maybe:
if(!preg_match('/^[\d,]+$/', $string)) {
//error
}
However this will not error on a single number with no commas.
Answer
Solution:
Use
\s+|,+\s*$
See proof
EXPLANATION
NODE EXPLANATION
PHP:
preg_replace('/\s+|,+\s*$/', '', $input)
Answer
Answer
Answer
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: use the option --with-all-dependencies (-w) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.