How can I remove unwanted code from a PHP string?

Solution 1: Using PHP Replacement Functions

You can replace content in a string using either str_replace() or preg_replace():


// Simple string replacement
str_replace('look', 'replace', $context);

// Regular expression replacement
preg_replace('pattern', 'replace', $context);

Notes:

str_replace() → replaces exact matches of a string.

preg_replace() → uses regular expressions, allowing more flexible and pattern-based replacements.

Solution 2: Sanitizing or Replacing Strings

Depending on your goal, you have different options for handling string replacement or sanitization:

1. Prevent HTML rendering:
Use htmlspecialchars() to convert special characters to HTML entities:


$safeString = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');

2. Sanitize for database input (MySQL):
Use mysql_real_escape_string() (or the modern equivalent mysqli_real_escape_string()) to safely include strings in queries:


$safeString = mysqli_real_escape_string($conn, $string);

3. Simple string replacement:
You can replace all instances of a substring using str_replace() or str_ireplace() (case-insensitive):


$newString = str_replace("look", "replace", $string);
$newString = str_ireplace("look", "replace", $string); // case-insensitive