问题
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