Current Location: Home> Latest Articles> stripos + substr_replace implements inserting content into strings

stripos + substr_replace implements inserting content into strings

M66 2025-06-03

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.

1. Function introduction

1. stripos()

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 .

2. substr_replace()

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

2. Examples of implementing string insertion

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。";
}
?>

Output result:

 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.

3. Practical scenarios

  1. Dynamically generated content : such as inserting slogans or guide links into the article.

  2. Automated text processing : For example, automatically insert instructions in customer email templates based on keywords.

  3. Content management system development : for example, add HTML elements after a specific tag.

4. Summary

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.