简体   繁体   中英

How to find and identify a specific part of a string?

I am making a search site where users can find stuff with my table.

Searching works great, but I want the ability to allow users to search instead with Google or Bing result. I would like people to identify that they want to use a specific search engine by indicating a / after the query.

So for example a search for something /google would send the search to Google. Likewise for Bing.

You could use a regexp to extract these parts of the query string. eg

preg_match_all('(?=^|\s)/[a-z]+\b', $query, $matches)

Would pull out all tokens that started with a slash and were followed by one or more letters from your query. You could then read through these tokens and decide what action to take on each one.

This regexp solution is robust because it should allow these (space separated) tokens to appear anywhere in your query string, or even to have multiple tokens in a query string.

You might then also want to use preg_replace(...) to strip these tokens from the query so that you can process the rest of the search text.

If you're looking for Google and Bing, or a small number of search engines, you can try:

if (strpos('/google',$_GET['q']) !== false) {
    header('Location: http://www.google.com/q='.str_replace('/google','',$q).'+site:example.com');
    exit;
} else if (strpos('/bing',$_GET['q']) !== false) {
    header('Location: http://www.bing.com/search?q='.str_replace('/bing','',$q).'+site:example.com');
    exit;
}

Note, you need to add this to your page before any text is outputted to PHP's output buffer (due to the header() function call). This means, before PHP has been instructed to write anything out to the page. Otherwise, you will get an error on your PHP page.

use preg_match to check the last part of the search string for /search_engine .

if it exists then redirect them to

http://www.google.com/search?q=site%3Adomain.com+search+string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM