In PHP, processing strings is one of the most common tasks in daily development. Sometimes, we need to insert a piece of text at a specific location in the string. This requirement can be achieved by combining the stripos() and substr_replace() functions. This article will use specific examples to describe how to use these two functions to complete the insertion operation of strings.
stripos() is used to find where a string first appears in another string (case insensitive).
int stripos ( string $haystack , mixed $needle [, int $offset = 0 ] )
$haystack : original string
$needle : The substring to be found
Return value: If found, return the first occurrence location; if not found, return false .
substr_replace() is used to replace a part of a string.
mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )
$string : original string
$replacement : What to insert
$start : the location where the replacement begins
$length (optional): The length to be replaced, if it is 0, it is equivalent to the insertion operation
Suppose we have a piece of text that wants to insert a link after a keyword, we can do this:
<?php
$text = "Welcome to our official website,Get more information。";
$keyword = "Official website";
$insert = "(Please visit https://m66.net Learn more)";
// Find the location of keywords in the original string
$pos = stripos($text, $keyword);
if ($pos !== false) {
// Calculate the insertion position:After the keyword
$insert_pos = $pos + strlen($keyword);
// Insert text
$new_text = substr_replace($text, $insert, $insert_pos, 0);
echo $new_text;
} else {
echo "Keyword not found。";
}
?>
Welcome to our official website(Please visit https://m66.net Learn more),Get more information。
This example shows how to insert additional information after a keyword without destroying the original string structure.
Dynamically generated content : such as inserting slogans or guide links into the article.
Automated text processing : For example, automatically insert instructions in customer email templates based on keywords.
Content management system development : for example, add HTML elements after a specific tag.
Finding insertion points through stripos() and string operations with substr_replace() is an efficient and flexible way, suitable for a variety of string insertion scenarios. I hope this article can help you better master string processing techniques in PHP.