How to get the last character or letter of a string

2

I'm trying to get the last number after the last dash that is the last rallite - of a string like this

Profesores-de-Barahona-demandan-calidad-del-almuerzo-escolar-y-mejorar-plantas-fsicas-3

This string comes from a URL which the last number is the id of the post so I need to extract that id to then make a query to the database try with explode in this way but it returns me from the first dash -

$id=explode("-",$_GET["view"]);

this returns me de

Any ideas on how to extract that last number? thanks in advance

    
asked by andy gibbs 25.11.2018 в 16:51
source

3 answers

3

You can do it as follows:

<?php

$cadena = "Profesores-de-Barahona-demandan-calidad-del-almuerzo-escolar-y- 
           mejorar-plantas-fsicas-3";

echo substr($cadena, strrpos($cadena, '-') + 1);

//RESULTADO 3

EXPLANATION

  • substr returns the specific part of a string
  • strrpos gets the last position where - appears
  • when using +1 we get the value that is after the last - which in this case is the number 3
  • answered by 25.11.2018 / 17:00
    source
    2

    Assuming that your $ GET ['view'] is a string:

    <?php
     $cadena = "Profesores-de-Barahona-demandan-calidad-del-almuerzo-escolar-y-mejorar-plantas-fsicas-3";
     $part=explode("-",$cadena); 
     $id = end($part);
     var_dump($id);exit();
    

    with the end () function of php you get the last element of an array

        
    answered by 25.11.2018 в 17:01
    2

    If all your URL are going to have at the end the id you need, you can simply do the following:

    $cadena = "Profesores-de-Barahona-demandan-calidad-del-almuerzo-escolar-y-mejorar-plantas-fsicas-3";
    $id = substr($cadena, -1);
    echo $id;
    

    You save in $id the number you want and then use it wherever you want. Greetings.

        
    answered by 25.11.2018 в 17:11