美好的一天。
有数字和其他符号时我有字符串(例如1412%2Fall
)
请告诉我如何将字符串修剪为不是数字的符号?
P.S。:例如。 1412%2Fall
结果应该是1412
;对于前23422345Dc#5
结果应该是23422345
,和其他...
使用PHP的preg_match
函数:
$str = "1412%2Fall";
$match = array();
preg_match("/^[0-9]+/",$str,$match);
你可以在$match[0]
找到你的结果。
只需使用(int)
或intval()
或preg_match
。
(int)
和intval()
几乎都做同样的工作。但是,将修剪字符串开头的零(s)。
使用preg_match
可以帮助保持起始零点。
Try the code below
preg_match("/^[0-9]+/", "1412%2Fall", $result1);
echo $result1[0]; //output: 1412
preg_match("/^[0-9]+/", "01412%2Fall", $result2);
echo $result2[0]; //output: 01412 (keeps the zero)
echo (int) '1412%2Fall'; //output: 1412
echo (int) '01412%2Fall'; //output: 1412
echo intval( '1412%2Fall' ); //output: 1412
echo intval( '01412%2Fall' ); //output: 1412
你绝对可以使用正则表达式,但这也可以:
$some_string = "321312mcvsdf";
$number = (int) $some_string; //321312
尝试使用preg_replace('/\D/', '', $youstring)