Pergunta

I am trying to create a Zend_Controller_Router_Route_Regex route to process URLs in the following form:

search?q=chicken/page=2 where the first regex subpattern would be chicken and second one would be 2. As for the second part where page=2, I want to make it optional if it is the first page, that is page=1. So another url such as search?q=chicken would also be valid and is equivalent to search?q=chicken/page=1.

Here is my attempt albeit without any success, but to give you a better picture of what I am trying to do.


        $route = new Zend_Controller_Router_Route_Regex(             
            'search\?q=([a-zA-Z0-9]+)(?:/page=(\d+))',
            array( 
                'page'=> '1',
             'module' => 'default', 
             'controller' => 'search', 
             'action' => 'index' ), 
            array( 1 => 'query', 2 => 'page' ),
            'search?=%s/page=%d');
        $router->addRoute('search', $route);

The problem here is I cant compose the correct regex.

Thanks in advance.

EDIT #1

The correct regex, as pointed out by MA4, is 'search\?q=([a-zA-Z0-9]+)(?:/page=(\d+))?'

The real problem is pointed by Darryl. Here is a little bit more info to put things into perspective.

My search text box and button

    <form action="/search" method="get">
            <input type="text" name="q" />
            <input type="submit" value="Search" />
    </form>

Every time I press the search button, I get the search?q=[text] request. How do I force it to go through the regex match route?

Here is what i want to do, however the code does not work

    if($this->getRequest()->getParam('query')){
        // redirect success
    } else {
        $url = "search?q=" . $this->_getParam('q');            
        $this->_redirect(route('search'), array('code' => 301 ));
    }
Foi útil?

Solução

/search?q=chicken/page=2 is not parsable by Zend Frameworks' router. The router will only see /search.

The router relies on the Path Info provided by the server and anything after the ? is the query string.

You would need to use a path such as this:

/search/[word]        (default page 1)
/search/[word]/[page] 

In which case your regex would become much simpler.

Outras dicas

make the second part optionnal by adding a ? after it:

search\?q=([a-zA-Z0-9]+)(?:/page=(\d+))?
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top