1

I am trying to find out where the position of a string occurs in another string.

I can use strpos but this returns the character position, and I am looking for the word count. For example:

$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
Shaun
  • 73
  • 1
  • 6
  • If you know where the string is, you could extract before that and use https://stackoverflow.com/questions/4786802/how-to-count-the-words-in-a-specific-string-in-php – Nigel Ren May 27 '20 at 13:40

1 Answers1

2

You can do this very simple, like this:

<?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

Just extract the string in Front of $needle and count the words. Add a +1 if you want the number of the first word from $needle, or leave as is to get the count of all words in front of it.

Frederick Behrends
  • 2,995
  • 21
  • 45
  • 2
    `str_word_count`!!!! A decade of PHP programming and I'm still learning about obscure but helpful string functions that are built into the language. ;) – Chris Haas May 27 '20 at 13:56