首页 > 解决方案 > 字符串中匹配的PHP字数位置

问题描述

我试图找出一个字符串的位置出现在另一个字符串中的位置。

我可以使用 strpos 但这会返回字符位置,我正在寻找字数。例如:

$haystack = 'The letters PHP stand for PHP: Hypertext Preprocessor. PHP originally stood for. Personal Home Page Tools.';
$needle = 'PHP: Hypertext Preprocessor';
magic_function($haystack, $needle); // This should return 6

标签: php

解决方案


你可以很简单地做到这一点,像这样:

<?php

function magic_function($haystack, $needle){

    $strBeforeNeedle = substr($haystack, 0, strpos($haystack, $needle));
    $wordCount = str_word_count($strBeforeNeedle);

    return $wordCount;

}

$haystack = 'The letters PHP stand for PHP: Hypertext Preprocessor. PHP originally stood for. Personal Home Page Tools.';
$needle = 'PHP: Hypertext Preprocessor';
echo magic_function($haystack, $needle); // This should return 6

只需提取前面的字符串$needle并计算单词。+1如果您想要 中的第一个单词的数量,请添加 a $needle,或者保持原样以获取其前面所有单词的数量。


推荐阅读