【问题标题】:How to search text using php if ($text contains "World")如何使用 php 搜索文本 if ($text contains "World")
【发布时间】:2011-04-26 10:09:40
【问题描述】:

如何使用 php 搜索文本?

类似:

<?php

$text = "Hello World!";

if ($text contains "World") {
    echo "True";
}

?>

除了用工作条件替换if ($text contains "World") {

【问题讨论】:

标签: php string search text


【解决方案1】:

最好的解决办法是我的方法:

在我的方法中,只检测到完整的单词,但在其他方式中则不是。

例如:

$text='hello world!'; 

if(strpos($text, 'wor') === FALSE) { 
   echo '"wor" not found in string'; 
}

结果:strpos 返回了true!!!但在我的方法中返回false

我的方法:

public function searchInLine($txt,$word){

    $txt=strtolower($txt);
    $word=strtolower($word);
    $word_length=strlen($word);
    $string_length=strlen($txt);
    if(strpos($txt,$word)!==false){
        $indx=strpos($txt,$word);
        $last_word=$indx+$word_length;
        if($indx==0){
            if(strpos($txt,$word." ")!==false){
                return true;
            }
            if(strpos($txt,$word.".")!==false){
                return true;
            }
            if(strpos($txt,$word.",")!==false){
                return true;
            }
            if(strpos($txt,$word."?")!==false){
                return true;
            }
            if(strpos($txt,$word."!")!==false){
                return true;
            }
        }else if($last_word==$string_length){
            if(strpos($txt," ".$word)!==false){
                return true;
            }
            if(strpos($txt,".".$word)!==false){
                return true;
            }
            if(strpos($txt,",".$word)!==false){
                return true;
            }
            if(strpos($txt,"?".$word)!==false){
                return true;
            }
            if(strpos($txt,"!".$word)!==false){
                return true;
            }

        }else{
            if(strpos($txt," ".$word." ")!==false){
                return true;
            }
            if(strpos($txt," ".$word.".")!==false){
                return true;
            }
            if(strpos($txt," ".$word.",")!==false){
                return true;
            }
            if(strpos($txt," ".$word."!")!==false){
                return true;
            }
            if(strpos($txt," ".$word."?")!==false){
                return true;
            }
        }
        }

    return false;
}

【讨论】:

  • 您能解释一下您的方法如何胜过内置 strpos 或它有什么优势吗?
  • 在我的方法中,只检测到完整的单词,但在其他方式中却不是。例如:$text='hello world!'; if(strpos($text, 'wor') === FALSE) { echo '"wor" not found in string'; } 结果:strpos 返回真!!!但在我的方法中返回 false。
  • 谢谢;我建议将您对答案的评论添加到您的答案中,以使这一点更清楚
【解决方案2】:
  /* https://ideone.com/saBPIe */

  function search($search, $string) {

    $pos = strpos($string, $search);  

    if ($pos === false) {

      return "not found";     

    } else {

      return "found in " . $pos;

    }    

  }

  echo search("world", "hello world");

在线嵌入 PHP:

body, html, iframe { 
  width: 100% ;
  height: 100% ;
  overflow: hidden ;
}
&lt;iframe src="https://ideone.com/saBPIe" &gt;&lt;/iframe&gt;

【讨论】:

  • 重新发明轮子很多?
【解决方案3】:

如果您正在寻找一种算法来根据多个词的相关性对搜索结果进行排名,这里有一种仅使用 PHP 生成搜索结果的快速简便的方法。

向量空间模型在PHP中的实现

function get_corpus_index($corpus = array(), $separator=' ') {

    $dictionary = array();
    $doc_count = array();

    foreach($corpus as $doc_id => $doc) {
        $terms = explode($separator, $doc);
        $doc_count[$doc_id] = count($terms);

        // tf–idf, short for term frequency–inverse document frequency, 
        // according to wikipedia is a numerical statistic that is intended to reflect 
        // how important a word is to a document in a corpus

        foreach($terms as $term) {
            if(!isset($dictionary[$term])) {
                $dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
            }
            if(!isset($dictionary[$term]['postings'][$doc_id])) {
                $dictionary[$term]['document_frequency']++;
                $dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
            }

            $dictionary[$term]['postings'][$doc_id]['term_frequency']++;
        }

        //from http://phpir.com/simple-search-the-vector-space-model/

    }

    return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}

function get_similar_documents($query='', $corpus=array(), $separator=' '){

    $similar_documents=array();

    if($query!=''&&!empty($corpus)){

        $words=explode($separator,$query);
        $corpus=get_corpus_index($corpus);
        $doc_count=count($corpus['doc_count']);

        foreach($words as $word) {
            $entry = $corpus['dictionary'][$word];
            foreach($entry['postings'] as $doc_id => $posting) {

                //get term frequency–inverse document frequency
                $score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);

                if(isset($similar_documents[$doc_id])){
                    $similar_documents[$doc_id]+=$score;
                }
                else{
                    $similar_documents[$doc_id]=$score;
                }

            }
        }

        // length normalise
        foreach($similar_documents as $doc_id => $score) {
            $similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
        }

        // sort fro  high to low
        arsort($similar_documents);
    }   
    return $similar_documents;
}

您的情况

$query = 'world';

$corpus = array(
    1 => 'hello world',
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

结果

Array
(
    [1] => 0.79248125036058
)

匹配多个单词和多个短语

$query = 'hello world';

$corpus = array(
    1 => 'hello world how are you today?',
    2 => 'how do you do world',
    3 => 'hello, here you are! how are you? Are we done yet?'
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

结果

Array
(
    [1] => 0.74864218272161
    [2] => 0.43398500028846
)

来自How do I check if a string contains a specific word in PHP?

【讨论】:

  • 为什么数组的最后一行 (3) 没有被计算?它以“hello”开头,但没有显示在最终结果中
【解决方案4】:

在我看来,strstr() 比 strpos() 更好。因为 strstr() 兼容 PHP 4 和 PHP 5。而 strpos() 只兼容 PHP 5。请注意部分服务器没有 PHP 5

【讨论】:

  • 嗯 - PHP5 于 2004 年首次发布。如果与 PHP4 的兼容性确实是个问题,我建议你换一个不同的托管公司。
【解决方案5】:

这可能是您正在寻找的:

<?php

$text = 'This is a Simple text.';

// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');

// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>

是吗?

或者这样:

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

甚至这个

<?php
$email  = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>

您可以在此处的文档中阅读所有关于它们的信息:

http://php.net/manual/en/book.strings.php

【讨论】:

    【解决方案6】:

    您需要的是 strstr()(或 stristr(),就像 LucaB 指出的那样)。像这样使用它:

    if(strstr($text, "world")) {/* do stuff */}
    

    【讨论】:

    • strpos 或 stripos 更适合 OP 给出的用例 - strstr 不厌其烦地构造一个新字符串,只是被丢弃了......
    • 添加到 Paul 的评论,来自strstr() 的 PHP 手册:“如果您只想确定某个特定的针是否出现在 haystack 中,请改用更快且内存占用更少的函数 strpos()。 "
    • 实际上,在给定原始示例的情况下,使用 strpos 而不是 strstr 是一种不合理的微优化。返回的字符串被浪费了,但是基于 single 文本搜索的“性能”来做出决定似乎并不明智。
    • 那么,你为什么要以一种或另一种方式争论它,@mario!似乎是在浪费时间.... ;-)
    【解决方案7】:

    在您的情况下,您可以使用strpos()stripos() 进行不区分大小写的搜索:

    if (stripos($text, "world") !== false) {
        echo "True";
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-14
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2021-06-01
      • 1970-01-01
      • 2017-11-03
      • 2018-03-19
      相关资源
      最近更新 更多