【问题标题】:How to get only the number from a string? [duplicate]如何只从字符串中获取数字? [复制]
【发布时间】:2015-06-13 05:16:54
【问题描述】:

我有这样的字符串:

第 001 课:完成

我只想获取数字部分,在本例中为001

我试过这个:

  $str = the_title();
  preg_match_all('!\d+!', $str, $matches);
  $number = implode(' ', $matches[0]);
  echo $number;

echo $number 再次输出整个字符串:Lesson 001: Complete

如何正确地做到这一点?

【问题讨论】:

  • 您的上述查询有效
  • 输出'001'没有问题。
  • 是的,它工作正常,你有什么问题?
  • 正如我对@ʰᵈˑ 所说的那样,如果我做$s = "Lesson 001: Complete"; 会起作用,但当我做$s = the_title(); 时不会起作用,即使它们的输出是相同的。不知道为什么。
  • @alexchenco 让我猜猜:var_dump(the_title());,你会得到NULL,对吧?你知道为什么? Because the function prints this, but doesn't return it! 解决方案?使用:get_the_title()(给我 100 分 :)?)

标签: php


【解决方案1】:

你可以试试/\d+/

$str = the_title();
preg_match_all('/\d+/', $str, $matches);
echo $matches[0]; 

【讨论】:

    【解决方案2】:

    filter_var

    您可以使用filter_var 并清理字符串以仅包含整数。

    $s = "Lesson 001: Complete";
    echo filter_var($s, FILTER_SANITIZE_NUMBER_INT);
    

    https://eval.in/309989

    preg_match

    您可以使用正则表达式仅匹配整数。

    $s = "Lesson 001: Complete";
    preg_match("/([0-9]+)/", $s, $matches);
    echo $matches[1];
    

    https://eval.in/309994

    【讨论】:

    • 出于某种原因,如果我做$s = "Lesson 001: Complete";,但当我做$s = the_title(); 时却不行,即使他们的输出是一样的。很奇怪。
    • @alexchenco 见stackoverflow.com/questions/29511413/…(Rizier123 获得 100 分)
    猜你喜欢
    • 2015-07-07
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    相关资源
    最近更新 更多