There is a string that contains numbers, - , spaces between them, and cm : $string = 50 — 55 см

Numbers may be different.

How to delete everything and leave only the last number: 55 . Without letters, without spaces and dashes?

Tried using preg_replace('/см/','',$string); but so i will remove only см

Closed due to the fact that off-topic participants Wiktor Stribiżew , Dmitry Kozlov , Edward , aleksandr barakin , freim March 7 at 17:50 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • " Learning tasks are allowed as questions only on the condition that you tried to solve them yourself before asking a question . Please edit the question and indicate what caused you difficulties in solving the problem. For example, give the code you wrote, trying to solve the problem "- Wiktor Stribiżew, Dmitry Kozlov, Edward, aleksandr barakin, freim
If the question can be reformulated according to the rules set out in the certificate , edit it .

    4 answers 4

     $string = '50 — 55 см'; echo preg_replace('/^.*?\b(\d+)\hсм$/m', '$1', $string); 
       preg_match_all('/\d+/', '50 — 55 см', $matches); echo end($matches[0]); 

      The regular expression: /\d+/ will select all the substrings in which one or more (quantifier + ), digit ( \d ) is found, and all other characters will be ignored.

      All matches are placed in the $matches[0] array. The end() function will return the last element of the array, the number 55.

      • 2
        The necessary element can be obtained without the help of additional functions, if the template is correctly written: ~(\d+)\hсм$\K~ - Edward

      Made awry, mb there are better options:

       if(preg_match('/см/i',$string)){ $newvalue = strpos($string,"—"); //находим позицию символа $string = trim(substr($string,0,$newvalue)); //делим по треб. символу и удаляем возможные пробелы } 

        As an option:

         $string = '50 — 55 см'; $num = preg_replace('/.*\D+(\d+)\D+$/i', '$1', $string);