从字符串中提取PHP中的数字+忽略<sup>内容

时间:2019-12-10 14:00:31

标签: php

我有2种类型的字符串:

  1. 356 Hello World!
  2. 6法国,您好! 2,5

我使用此代码提取数字,实际上我只需要从头开始输入数字

$int_image_id = (int) filter_var(get_the_title(), FILTER_SANITIZE_NUMBER_INT);

结果是:

  1. 356
  2. 625(但应为6)

3 个答案:

答案 0 :(得分:2)

如果数字始终以字符串开头,则也可以简单地使用intval

$int_image_id = intval(get_the_title());

答案 1 :(得分:0)

希望得到帮助:

$int_image_id = (int) get_the_title();

如果$int_image_id = '6 Hello France! 2,5';

输出:

6

我检查了。

答案 2 :(得分:0)

另一种方法是使用正则表达式 preg_match('/\d+/', $string, $matches); 上一行将搜索数字并将其添加到$matches数组中。

<?php
$string = '6 Hello France! 2,5';

$matches = array();
preg_match('/\d+/', $string, $matches);
print_r($matches)
?>