如何摆脱PHP中的字符串元素?

时间:2010-02-08 16:04:56

标签: php string

客户ID文字有customer_id + Domain_details,例如:998787+nl现在我只想拥有998787而不是+nl,如何在php中实现这一点

问题:

我有9843324+nl之类的数字,现在我想摆脱包括+在内的所有元素,最后只有9843324,所以我应该如何在php中执行此操作?

现在我正在$o_household->getInternalId给我9843324+nl,但我想要9843324,我该如何实现?

感谢。

感谢。

更新

    list($customer_id) = explode('+',$o_household->getInternalId());

这会解决我的问题吗?

6 个答案:

答案 0 :(得分:2)

如果您不想保留前导零,只需将其转换为整数。

$theID = (int)"9843324+nl";
// $theID should now be 9843324.

如果+只是一个分隔符,之前的sutff可以是非数字,请使用

$val = "9843324+nl";
$theID = substr($val, 0, strcspn($val, '+'));
// $theID should now be "9843324".

答案 1 :(得分:2)

简单方法?只需将其转换为int,它就会丢弃额外的东西。

<?php
$s = '998787+nl';
echo (int)$s;
?>

输出:

998787

答案 2 :(得分:1)

如果您需要保留字符串值,可以使用substr将字符串剪切到其起始索引,从最后一个字符开始第3个,省略域详细信息 +nl < / em>的

$customer_id = substr($o_household->getInternalId, 0, -3);

答案 3 :(得分:1)

作为一个稍微更通用的解决方案,这个正则表达式将删除字符串$str中不是数字的所有内容,并将新字符串(数字集,因此可以视为整数)放入$num

$num = preg_replace('/[^\d]/', '', $str);

答案 4 :(得分:1)

<?php
$plusSignLoc = strpos($o_household->getInternalId, "+");
$myID = substr($o_household->getInternalId, 0, $plusSignLoc);

//Debug (Verification)
echo $myID;
?>

这将找到+号,并确保删除之后的所有内容和所有内容。

答案 5 :(得分:0)

查看explode()功能,并使用+作为分隔符。