0

Quick question:

I have strings in the form of '121', '9998', etc. They are literally numbers surrounded by the single quotes.

How can I remove these quotes and cast them as integers? I'm passing to another program that needs them to be integers.

Thanks.

1
  • As you can see from various responses, you should clarify if the single quote is part of the string. i.e. Do you mean $str = '123', or do you mean $str = "'123'"? Commented Sep 14, 2011 at 3:35

3 Answers 3

4

Use trim() and intval():

$n = intval(trim($str, "'"));
Sign up to request clarification or add additional context in comments.

Comments

4

There are a few ways to do this, but the most common are:

$int = intval($string);

Or, my preference:

$int = (int)$string;

Since $string has a literal single quote, you can trim() it first by taking advantage of its second parameter.

$int = (int)trim($string, "'");

Remember that PHP is a weak typed, dynamic language.

3 Comments

"They are literally numbers surrounded by the single quotes."
casting is better than intval in term of speed
@Tarek: even though you're literally right, it doesn't make sense until you have less than millions of castings
3
$int = (int)trim("'121'", "'");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.