How to get rid of extra elements in string literal in php?
I have number like 9843324+
and now I want to get rid of +
at the end and only have 9843324
and so how should I do this in php ?
Right now I am doing $customer_id = explode('+',$o_household->getInternalId);
also $o_household->getInternalId
returns me 9843324+ but I want 9843324, how can 开发者_Go百科I achieve this ?
Thanks.
if you just want to pop the + off the end, use substr
.
$customer_id = substr($o_household->getInternalId, 0, -1);
or rtrim
$customer_id = rtrim($o_household->getInternalId, "+");
You can use a regeular expression to remove anything that isn't a number
$newstr = preg_replace("/[^0-9]+/","",$str);
$customer_id = rtrim ( $o_household->getInternalId, '+' );
rtrim function reference
rtrim
removes the characters in the second argument (+
only in this case) from the end of a string.
In case there is no +
at the end of the string, this won't mess up your value like substr
.
This solution is obviously more readable and faster than, let's say preg_replace
too.
you could use intval($o_household->getInternalId)
Is there a reason you need to use explode? i would just use substr
as Andy suggest or str_replace
. Either would work for the example you provided.
You can use intval to get the integer value of a variable, if possible:
echo intval($str);
Be aware that intval will return 0 on failure.
精彩评论