2010-10-16 8 views
19

Come cercare il testo usando php?

Qualcosa di simile:

<?php 

$text = "Hello World!"; 

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

?> 

Tranne la sostituzione if ($text contains "World") { con una condizione di lavoro.

+0

Si potrebbe trovare [ 's ($ str) -> contiene ('Mondo')'] (https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/ src/Str.php # L93) e ['s ($ str) -> containsIgnoreCase ('World')'] (https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str .php # L105) utile, come trovato in [questa libreria standalone] (https://github.com/delight-im/PHP-Str). – caw

risposta

37

Nel tuo caso si può semplicemente usare strpos(), o stripos() per caso ricerca maiuscole:

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

funziona anche per le maiuscole e le maiuscole. – AMB

+0

Perfettamente funzionante – Vivek

8

Quello che vi serve è strstr() (o stristr(), come LucaB sottolineato). Utilizzare in questo modo:

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

strpos o stripos è migliore per il caso d'uso dato dall'OP - strstr va a tutti i problemi di costruire una nuova stringa, solo per essere buttato via ... –

+1

Aggiunta al commento di Paul, dal manuale PHP per [ 'strstr()'] (http://www.php.net/manual/en/function.strstr.php): "Se vuoi solo determinare se un determinato ago si verifica all'interno del pagliaio, usa il più veloce e con meno memoria funzione 'strpos()' invece. " – BoltClock

+0

Beh, in realtà, è una microottimizzazione irragionevole usare strpos su strstr dato l'esempio originale. La stringa restituita va sprecata, ma basare la decisione su "performance" per una ricerca di testo * single * non sembra ragionevole. – mario

2

Questo potrebbe essere quello che stai cercando:

<?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'); 
?> 

è vero?

O forse questo:

<?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"; 
} 
?> 

O anche questo

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

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

Potete leggere tutto su di loro nella documentazione qui:

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

1

a mio parere strstr () è migliore di strpos(). perché strstr() è compatibile sia con PHP 4 AND PHP 5. ma strpos() è compatibile solo con PHP 5. nota che parte dei server non ha PHP 5

+1

Uhm - PHP5 è stato rilasciato per la prima volta nel 2004. Se la compatibilità con PHP4 è davvero un problema, ti suggerisco di passare a una società di hosting diversa. – Edward

3

Se stai cercando un algoritmo per classificare i risultati di ricerca basati sulla rilevanza di più parole ecco un modo semplice e veloce di generare risultati di ricerca solo con PHP.

L'attuazione del modello di spazio vettoriale in 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; 
} 

nel tuo caso

$query = 'world'; 

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

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

RISULTATI

Array 
(
    [1] => 0.79248125036058 
) 

parole corrispondenti multipla nei confronti FRASI DI PIÙ

$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>'; 

RISULTATI

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

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

0
/* 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"); 

Embed PHP on-line:

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

+0

Reinventare la ruota molto? – MJoraid

Problemi correlati