skip to Main Content

I have a SEO URL like

lieferservice-pizzeria-da-persio-26-offenbach

in my bootstrap file I am trying to pase this URL and get ID of a shop which is in this is 26

Then I can read the database to get infos of the shop. What will be the best way to do this. have no idea.

4

Answers


  1. Best Solution

    $str = 'lieferservice-pizzeria-da-persio-26-offenbach';
    $int = intval(preg_replace('/[^0-9]+/', '', $str), 10);
    var_dump($int );
    

    Its return only int 26

    Login or Signup to reply.
  2. The proposed solution simply removes all non digits so you end up with only digits. This works if you can ensure that you’ll never have a digit in your string else than the string. So with a string like ‘lieferservice-pizzeria12-da-24-persio-26-offenbach’ you would get 122426 instead of the 26 you wanted to.

    If you want to ensure that you only accept -somedigit- as id you should use:

    preg_match("/-([0-9]+)-/", $input_line, $output_array);
    

    instead.

    What this actually does is really simple:

    It simply looks for the first string starting with a “-” followed by exclusive! digits and ending with “-” than it returns the whole string in $output_array[0] (in your example -26-) and the digit (the stuff inside the brackets) in $output_array[1] which equals 26 in your case.

    Login or Signup to reply.
  3. Assuming you have a function in your controller, let call it

    public function getUrl(){
    
    }
    

    The first think is to make CakePhp accept the type of URL you are passing (with special characters like “-“). In your route you can have this:

    Router::connect('/getUrl/:id', array('controller' => 'yourControllerName', 'action' => 'getUrl'), array('id' => '[0-9A-Za-z= -]+'));
    

    Now if you pass your URL as

    www.domain.com/getUrl/lieferservice-pizzeria-da-persio-26-offenbach
    

    Then back to your function

    public function getUrl(){
      $getValueFromUrl = $this->params['id'];
      // Use PHP explode function to get 26 out of $getValueFromUrl
    
    }
    
    Login or Signup to reply.
  4. that’s what routes are for. you can paramatized any part of url and access it in the request.in your case i think you want to combine some sort of a slug with an id separted by dash. that’s a piece of cake.

    Router::connect('/:slug-:id', array('controller' => 'yourController', 'action' => 'yourAction'), array('id' => '[0-9]+','slug' => '[a-zA-z-]+')); 
    
    //inside your action
    $id = $this->request->params['id'];
    $slug = $this->request->params['slug'];
    

    no nee for regex 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search