如何将字符串修剪为不是数字的符号? [关闭]

问题描述 投票:2回答:4

美好的一天。

有数字和其他符号时我有字符串(例如1412%2Fall

请告诉我如何将字符串修剪为不是数字的符号?

P.S。:例如。 1412%2Fall结果应该是1412;对于前23422345Dc#5结果应该是23422345,和其他...

php string
4个回答
3
投票

使用PHP的preg_match函数:

$str = "1412%2Fall";
$match = array();
preg_match("/^[0-9]+/",$str,$match);

你可以在$match[0]找到你的结果。


7
投票

只需使用(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

2
投票

你绝对可以使用正则表达式,但这也可以:

$some_string = "321312mcvsdf";
$number = (int) $some_string; //321312

1
投票

尝试使用preg_replace('/\D/', '', $youstring)

© www.soinside.com 2019 - 2024. All rights reserved.