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
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.