Как искать текст с помощью php, если ($text содержит "Мир")
Как искать текст с помощью php?
Что-то вроде:
<?php
$text = "Hello World!";
if ($text contains "World") {
echo "True";
}
?>
За исключением замены if ($text contains "World") {
на рабочее состояние.
6 answers
Что вам нужно, так это strstr()
( или stristr()
, как указал ЛукаБ). Используйте его следующим образом:
if(strstr($text, "world")) {/* do stuff */}
Если вы ищете алгоритм ранжирования результатов поиска на основе релевантности нескольких слов, здесь вы найдете быстрый и простой способ генерации результатов поиска только с помощью 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
)
Из Как мне проверить, есть ли строка содержит определенное слово в PHP?
Это может быть то, что вы ищете:
<?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 = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>
Вы можете прочитать все о них в документации здесь:
На мой взгляд, strstr() лучше, чем strpos(). потому что strstr() совместим как с PHP 4, так и с PHP 5. но strpos() совместим только с PHP 5. обратите внимание, что на части серверов нет PHP 5
/* 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 ;
}
<iframe src="https://ideone.com/saBPIe" ></iframe>