简体   繁体   English

如何查找和识别字符串的特定部分?

[英]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. 搜索效果很好,但我希望能够允许用户使用Google或Bing结果进行搜索。 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. 因此,例如,搜索某物/ google会将搜索结果发送给Google。 Likewise for Bing. 对于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. 然后,您可能还希望使用preg_replace(...)从查询中剥离这些标记,以便可以处理其余的搜索文本。

If you're looking for Google and Bing, or a small number of search engines, you can try: 如果您正在寻找Google和Bing或少量搜索引擎,则可以尝试:

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). 注意,在将任何文本输出到PHP的输出缓冲区之前(由于header()函数调用),需要将其添加到页面中。 This means, before PHP has been instructed to write anything out to the page. 这意味着,在未指示PHP将任何内容写到页面之前。 Otherwise, you will get an error on your PHP page. 否则,您将在PHP页面上收到错误消息。

use preg_match to check the last part of the search string for /search_engine . 使用preg_match检查/search_engine搜索字符串的最后一部分。

if it exists then redirect them to 如果存在,则将其重定向到

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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