In PHP development, we often need to search for a keyword within a string and determine its relative position in the text. For example, we may want to know whether a keyword appears in the first half or the second half of the text. This is a common requirement in content analysis, SEO, and even advertising.
This article will introduce how to calculate the relative position percentage of a keyword within a string using the stripos() and strlen() functions, along with some simple practical examples.
stripos() is a PHP function used to find the first occurrence of a substring in a string. The syntax is:
int stripos ( string $haystack , mixed $needle [, int $offset = 0 ] )
It returns the position of the first occurrence of $needle in $haystack (case-insensitive). If the keyword is not found, it returns false.
strlen() is used to get the length of a string. Its syntax is simple:
int strlen ( string $string )
It returns the total length of the string (in characters).
We can use the following formula to calculate the relative position percentage of a keyword within a string:
Relative Position Percentage = (Keyword Position / Total String Length) * 100
To avoid division by zero errors, basic error checks are also necessary. Below is a complete example:
<?php
$text = "Welcome to our website. For more information, please visit https://m66.net/page/about. We focus on high-quality content.";
$keyword = "information";
<p>$position = stripos($text, $keyword);<br>
$length = strlen($text);</p>
<p>if ($position !== false && $length > 0) {<br>
$percentage = ($position / $length) * 100;<br>
echo "The relative position of the keyword '{$keyword}' in the text is: " . round($percentage, 2) . "%";<br>
} else {<br>
echo "Keyword '{$keyword}' not found or the string is empty.";<br>
}<br>
?><br>
The output might look like this:
The relative position of the keyword 'information' in the text is: 34.88%
Content Summary Positioning
If you are generating a summary for an article, you can use the relative position of the keyword to determine whether it is included, enhancing the relevance of the summary.
Keyword Popularity Analysis
If multiple keywords appear in the earlier part of the text, they can be considered more “important,” influencing ranking strategies.
Ad Content Insertion
Based on the distribution of keywords in the “beginning, middle, or end” of the text, you can decide where to insert ad content to increase conversion rates.
stripos() and strlen() are a simple yet powerful combination for quickly obtaining the relative position of a keyword. This technique is applicable in various scenarios, including log analysis, SEO optimization, and content management systems. Mastering it will make text data handling much more efficient.