本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑方法1:利用is_numeric()函数<?php header("content-type:text/html;charset=utf-8"
本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑
方法1:利用is_numeric()函数
<?php
header("content-type:text/html;charset=utf-8");
function findNum($str) {
$str = trim($str);
if (empty($str)) {
echo '';
}else{
$result = '';
for ($i = 0; $i < strlen($str); $i++) {
if (is_numeric($str[$i])) {
$result .= $str[$i];
}
}
echo $result;
}
}
$str = '0我是123456一段测试的字789符串0';
findNum($str);
?>
利用for循环遍历字符串$str,使用is_numeric()函数判断$str[$i]
是否为数字字符。is_numeric()函数可以检测变量是否为数字或数字字符串。
在循环体中使用is_numeric($str[$i])判断该$str[$i]字符是不是数字字符;如果是则取出来,使用 “.=”拼接成数字子串。
看看输出结果:
01234567890
方法2:使用preg_replace()函数
<?php
$str ='0我是123456一段测试的字789符串0';
$result = preg_replace("/[^0-9]/", "", $str);
echo $result;
?>
--结束END--
本文标题: php怎么过滤字符串只获取数字
本文链接: https://www.lsjlt.com/news/270.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
2023-05-25
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0