php:解析字符串以获取字符串

时间:2015-12-15 12:17:43

标签: php string

如何在下面的下划线之前提取数字33

33_restoffilename.txt.

会像下面的工作吗?

int strPos = strpos("33_filename.txt", "_");
str num = substr ("33_filename.txt" , 0 , strPos );

6 个答案:

答案 0 :(得分:4)

如果命名约定始终为number_filename.ext,则可以使用explode()

//Put the filename into the variable $name
$name = "33_restoffilename.txt";

//Split the name by "_"
$parts = explode("_", $name);

//Get the first part of the name from the array (position 1)
$number = $parts[0];

//Output
echo $number;

这将输出

  

33

答案 1 :(得分:4)

有可能实现这个目标:

方法1:

$strPos = strpos("33_filename.txt", "_");
echo $num = substr("33_filename.txt" , 0 , $strPos );

方法2:

$str = '33_filename.txt';
$str_arr = explode('_', $str);
echo $num = $str_arr[0];

答案 2 :(得分:1)

使用strstr()

$str = '33_filename.txt';
$num = strstr($str, '_', true);

答案 3 :(得分:0)

方法 - 1

$getIntegerFromBeginning = substr($string, 0, strspn($string, "0123456789"));
echo $getIntegerFromBeginning;

方法 - 2

$getIntegerFromBeginning = explode("_", $string, 2);
echo  $getIntegerFromBeginning[0];

用完全字符串替换$ string。

答案 4 :(得分:0)

使用此

$string = '33_filename.txt';

$arrString = explode('_', $string);

echo $value = $arrString[0]; //Will output 33

答案 5 :(得分:0)

这非常简单,在这种情况下我们不需要这些字符串函数。只需进行类型转换,您将获得整数。这将是快速和简单的

$pp='33_restoffilename.txt';
echo (int)$pp;

无需复杂化