0

I'm creating my own search form in D7, and I need to sanitize the search text so that it is URL safe. I need to mimic the way that the views module does it because I'm using the search_api module and views.

In short, I need to make this:

"what is going on around here, anyway?"

look like this:

what+is+going+on+around+here%2C+anyway%3F

How do I do that?

2
  • urlencode() can do that I believe. php.net/manual/en/function.urlencode.php I'm not sure how Views does it though.
    – Citricguy
    Commented Aug 28, 2012 at 3:17
  • I have been looking all through the views codebase to try and figure out how they're doing it. They aren't using urlencode, though, I know that. Just ran a search to check it out and I didn't find anything.
    – ldweeks
    Commented Aug 28, 2012 at 3:25

2 Answers 2

1

Use the url() function to encode your URLs.

url("what is going on around here, anyway?");

this will return the string '/what%20is%20going%20on%20around%20here%2C%20anyway%3F'

You could also use this to get the full, absolute URL.

url("what is going on around here, anyway?", array('absolute' => TRUE));

You may also be interested in the l() function if you need html output.

0
0

For future reference, here is what I did:

function my_search_form_submit($form, &$form_state) {

  if ($form_state['values']['area'] == 'cookbook') {
    $search_string = 'http://example.com/cookbook?recipe-search=';
  }
  elseif ($form_state['values']['area'] == 'blog') {
    $search_string = 'http://example.com/blog?blog-search=';
  }

  $search_string = url($search_string . urlencode($form_state['values']['search_value']));

  $form_state['redirect'] = $search_string;
}
3
  • What is the initial value of $search_string in the first part of the url function and where does it come from? url($search_string...
    – Citricguy
    Commented Aug 28, 2012 at 4:16
  • Good question. Here it is: $search_string = 'http://mysite.com/blog?blog-search=';. Notice that I used the absolute URL. I had to do that to keep it from encoding the first part of the search string.
    – ldweeks
    Commented Aug 28, 2012 at 4:24
  • 1
    I just edited my answer to include the entire function.
    – ldweeks
    Commented Aug 28, 2012 at 4:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.