search in text , and select keywords by php

落花浮王杯 提交于 2019-12-24 08:24:01

问题


How are you ?

I have a text :

The Byzantines were able to regain control of the country after a brief Persian invasion early in the 7th century, until 639-42, when Egypt was invaded and conquered by the Islamic Empire by the Muslim Arabs. When they defeated the Byzantine Armies in Egypt, the Arabs brought Sunni Islam to the country. Early in this period, Egyptians began to blend their new faith with indigenous beliefs and practices, leading to various Sufi orders that have flourished to this day.[24] These earlier rites had survived the period of Coptic Christianity

I want to search in this text , and select the categories , tags

<?php // this is some tags in Array , but I don't know which tag is used in this text.
$search_words = array("Egypt , Persian , Islamic , USA , Japan , Spain , Saudi Arabia");

foreach($search_words as $value){
        stristr($longText, $search_words); // I know this is mistake
    }?>

I want to select which words($search_words) used in this easy.

I'm sorry for my language


回答1:


$words_found = array();
foreach ($search_words as $word) {
    if (stristr($longText, $word)) {
         $words_found[] = $word;
    }
}

$words_found is now an array containing all of the tags in the $search_words array which are present in the text.

Also, the syntax of your the array in your example is incorrect, it should be this:

$search_words = array("Egypt", "Persian", "Islamic", "USA", "Japan", "Spain", "Saudi Arabia");



回答2:


Without running a loop you can do this:

$str = <<< EOF
The Byzantines were able to regain control of the country after a brief Persian
invasion early in the 7th century, until 639-42, when Egypt was invaded and conquered
by the Islamic empire by the Muslim Arabs. When they defeated the Byzantine Armies in
Egypt, the Arabs brought Sunni Islam to the country. Early in this period, Egyptians
began to blend their new faith with indigenous beliefs and practices, leading to 
various Sufi orders that have flourished to this day.[24] These earlier rites had
survived the period of Coptic Christianity in Saudi Arab.
EOF;
$search_words = array("Egypt", "Persian", "Islamic", "USA", "Japan", "Spain",
                      "Saudi Arab");
preg_match_all('/\b[A-Z][a-z\d]*(?:\s+[A-Z][a-z\d]*)?\b/', $str, $arr);
print_r(array_intersect($search_words, $arr[0]));

OUTPUT:

Array
(
    [0] => Egypt
    [1] => Persian
    [2] => Islamic
    [6] => Saudi Arab
)


来源:https://stackoverflow.com/questions/10871590/search-in-text-and-select-keywords-by-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!