Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用php查找字符串中以特定leter或元素结尾和开头的单词_Php - Fatal编程技术网

如何使用php查找字符串中以特定leter或元素结尾和开头的单词

如何使用php查找字符串中以特定leter或元素结尾和开头的单词,php,Php,我使用str_word_count()计算一个单词在文本中出现的次数,但我真正想要的是只计算以'[word here]'开头和结尾的特定单词。 $text = "Degree binb 'Information-Systems', 'Computer-Science' , or other KM-relevant field required; graduate degree preferred."; $words = str_word_count($text, 1); $frequency

我使用str_word_count()计算一个单词在文本中出现的次数,但我真正想要的是只计算以
'[word here]'开头和结尾的特定单词。

$text = "Degree binb 'Information-Systems', 'Computer-Science' , or other KM-relevant field required; graduate degree preferred.";

$words = str_word_count($text, 1); 
$frequency = array_count_values($words);
arsort($frequency);
echo '<pre>';
print_r($frequency);
echo '</pre>';
使用
substr()
检查字符串的开头/结尾是否等于要搜索的其他字符串:

正如您所注意到的,若要从字符串末尾进行比较,请使用负$start值

对于长度参数,请使用
strlen()
获取字符串长度:


PHP伪代码示例:

$prefixed_words = find_words_prefix("Degree binb 'Information-Systems', 'Computer-Science' , or other KM-relevant field required; graduate degree preferred.", "D");

print_r($prefixed_words);

类似的函数可用于后置单词

要查找单引号中的所有单词,请使用带有
preg\u match\u all()的正则表达式

这将输出:

function find_words_prefix($text, $prefix)
{
  $words = array_filter(explode(' ', $text), 'strlen'); // get only non-emoty words
  $prefixed_words = array();
  $prefix_len = strlen($prefix);
 foreach ($words as $word)
{
if (strlen($word) < $prefix_len) continue; // no use testing this word as it is smaller than prefix
if ( 0 === strpos($word, $prefix) ) $prefixed_words[] = $word;
}
return $prefixed_words;
}
$prefixed_words = find_words_prefix("Degree binb 'Information-Systems', 'Computer-Science' , or other KM-relevant field required; graduate degree preferred.", "D");

print_r($prefixed_words);
$text = "Degree binb 'Information-Systems', 'Computer-Science' , or other KM-relevant field required; graduate degree preferred.";

preg_match_all("/'([^']+)'/", $text, $matches);

var_dump($matches[1]);
echo "Found " . count($matches[1]) . " matches." . PHP_EOL;
array(2) {
  [0] =>
  string(19) "Information-Systems"
  [1] =>
  string(16) "Computer-Science"
}
Found 2 matches.