0

I have strings like this:

Lesson 001: Complete

I want to only get the number part, in this case 001.

I tried this:

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

But echo $number outputs the entire string once again: Lesson 001: Complete

How to do this correctly?

alexchenco
  • 53,565
  • 76
  • 241
  • 413

2 Answers2

19

filter_var

You can use filter_var and sanitize the string to only include integers.

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

https://eval.in/309989

preg_match

You can use a regular expression to match only integers.

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

https://eval.in/309994

ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
  • For some reason works if I do `$s = "Lesson 001: Complete";` but not when I do `$s = the_title();` Even though their ouput is the same. Weird. – alexchenco Apr 08 '15 at 10:07
  • 1
    @alexchenco see http://stackoverflow.com/questions/29511413/how-to-get-only-the-number-from-a-string/29511466#comment47179172_29511413 (Rizier123 gets 100pts) – ʰᵈˑ Apr 08 '15 at 10:15
  • Note: FILTER_SANITIZE_NUMBER_INT - removes all characters *except* digits, plus and minus sign. – Leon Jun 18 '22 at 13:45
2

you can try with /\d+/

$str = the_title();
preg_match_all('/\d+/', $str, $matches);
echo $matches[0]; 
Naing Lin Aung
  • 3,373
  • 4
  • 31
  • 48