Jump to content

Search using or with sanitizer


Tom.
 Share

Recommended Posts

I'm building in search in which you can search tags by the following: "Typography, Css"

I initially thought to do a string replace of comma into a pipe and run it though a sanitizer.  However, selectorValue removes the pipe. First sanitizing the string then doing a string replace will leave a search like "Typograph| css" which wouldn't work because it's wrapped in quotes. 

I eventually came up with the following - which works:

		
		// Remove space and replace with pipe
		$search = preg_replace("/,\s*/", "|", $input->get->search);
		
		// Explode pipe into array
		$search = explode("|", $search);
		
		// Sanitize each value
		foreach($search as &$item) {
			$item = $sanitizer->selectorValue($item);
		}
		
		// Array back to string
		$search = implode("|", $search);
		
		$results = $pages->find("parent=/posts/, tags|category.title|title%=$search, limit=25, sort=-created");

However, I'm wondering if I'm missing something here? Is there a more effective way to do this?

Link to comment
Share on other sites

Not sure that you need to do the first pipe replace - you could just explode on commas and then trim(). You'll add the pipe when you implode.

Also, passing by reference in a foreach can catch you out so perhaps better to avoid it.

// Explode search input into array
$search = explode(",", $input->get->search);

// Sanitize each value
foreach($search as $key => $value) {
    $search[$key] = $sanitizer->selectorValue(trim($value));
}

But otherwise it looks fine to me; that's what I would do. :)

  • Like 3
Link to comment
Share on other sites

11 hours ago, AndZyk said:

You could also build your selector as array:


$results = $pages->find([
	['parent', '/posts/'],
	['tags|category.title|title', '%=', $search],
	['limit', '25'],
	['sort', '-created']
]);

That way you don't have to make the array back to an string and it is more readable for complex selectors. ;)

Perfect! I knew I was taking the long way around! There's always a simpler way in ProcessWire I've found :) 

		$results = $pages->find([
			['parent', '/posts/'],
			['tags|category.title|title', '%=', explode(",", $input->get->search), 'selectorValue'],
			['limit', '25'],
			['sort', '-created']
		]);

 

  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...