In PHP, stripos and in_array functions are very common tools to determine whether a keyword exists in multiple fields or arrays. This article will introduce to you how to combine these two functions to achieve this requirement.
The stripos function is used to find where a string first appears in another string. It is similar to the strpos function, but stripos is case-insensitive.
grammar:
stripos($haystack, $needle, $offset)
$haystack : The string to be found.
$needle : The keyword to look for.
$offset : optional, specify where to start searching.
If the keyword is found, it returns its position in the $haystack string , otherwise it returns false .
The in_array function is used to check whether a value exists in an array.
grammar:
in_array($needle, $haystack, $strict)
$needle : The value to be found.
$haystack : The array to be found.
$strict : optional, indicating whether to perform strict type checks.
Return true if $needle exists in $haystack , otherwise false .
We can combine these two functions to determine whether multiple fields contain a keyword. Suppose we have an array with multiple fields and we want to find out if a specific keyword appears in these fields.
<?php
// Define an array of multiple fields
$fields = [
'title' => 'Welcome to our website!',
'description' => 'Find great products at our online store.',
'content' => 'Visit our store today for amazing deals!'
];
// Keywords to search
$keyword = 'store';
// use in_array and stripos Determine whether keywords appear in multiple fields
$found = false;
foreach ($fields as $field => $value) {
if (stripos($value, $keyword) !== false) {
echo "Keyword '$keyword' found in the '$field' field.\n";
$found = true;
}
}
if (!$found) {
echo "Keyword '$keyword' not found in any field.\n";
}
?>
explain:
We define an array containing multiple fields such as title , description , and content .
We then iterate through these fields and use the stripos function to find out if the keyword appears in these fields.
If found, we output the name of the field. If not found, the output is not found.
Suppose we want to replace the URL in the string with the domain name m66.net , we can use stripos to find the URL and replace it through string operations. Here is a simple example:
<?php
// Original content
$content = "Check out our site at http://example.com and also visit our blog at http://example.com/blog";
// Find URL and replace the domain name
$pattern = '/http(s)?:\/\/([a-zA-Z0-9\-\.]+)(\/[^\s]*)?/';
$replacement = 'http://m66.net$3';
// use preg_replace Make a replacement
$new_content = preg_replace($pattern, $replacement, $content);
// Output the replaced content
echo $new_content;
?>
explain:
Here we use regular expressions to match URLs.