PHP function to delete all between certain character(s) in string
Stripping substrings from a larger string based on specific delimiters is a common requirement when cleaning up HTML snippets, parsing logs, or sanitizing user input. The goal here is straightforward: locate an opening marker and a closing marker within a source string, then remove everything between them, inclusive of the markers themselves.
Consider a scenario where you have a string containing mixed content, such as valid text interspersed with script tags that need removal:
$string = 'Some valid and <script>some invalid</script> text!';
// Desired output: 'Some valid and text!'
While regex is the go-to tool for pattern matching in PHP, a naive approach using preg_replace can sometimes be overkill or introduce subtle bugs if not constructed carefully. A procedural solution using native string functions often offers better readability and predictable behavior when the delimiters are known constants.
The Procedural Approach
The most robust way to solve this without relying on complex regular expressions is to leverage PHP's strpos and substr. This method explicitly finds the start index, calculates the end index, and reconstructs the string by concatenating the parts before and after the target range.
Here is an implementation that handles the requirement to include both delimiters in the deletion:
function delete_all_between($char1, $char2, $string) {
// Find the first occurrence of the opening character
$start_pos = strpos($string, $char1);
// If the opening character is not found, return the original string
if ($start_pos === false) {
return $string;
}
// Find the first occurrence of the closing character after the opening one
$end_pos = strpos($string, $char2, $start_pos);
// If the closing character is not found, we have an incomplete block.
// Depending on business logic, you might want to return original or throw error.
if ($end_pos === false) {
return $string;
}
// Calculate the position immediately after the closing character
$new_end_pos = $end_pos + strlen($char2);
// Reconstruct the string by taking parts before start and after new_end
return substr($string, 0, $start_pos) . substr($string, $new_end_pos);
}
This function works by first establishing the boundary of the data to be removed. It checks for the existence of $char1. If found, it then searches specifically for $char2 starting from the position immediately following $char1. This ensures that if multiple occurrences exist, only the first matching pair is processed in a single call. The final return statement concatenates the prefix (everything before $char1) with the suffix (everything after $char2).
Handling Edge Cases and Trade-offs
A critical detail often overlooked is the handling of unclosed tags or mismatched delimiters. In the example above, if $char2 does not appear after $char1, the function returns the original string unchanged. This is generally safer than throwing an exception or silently truncating the data, as it prevents data loss during partial parsing errors.
Another consideration is case sensitivity. The standard strpos function is case-sensitive. If your input might contain <SCRIPT> alongside <script>, you would need to convert the delimiters to a consistent case before searching or use stripos. However, for strict HTML parsing where tags are expected to be lowercase, the default behavior is usually sufficient and more performant.
Performance-wise, this procedural approach avoids the overhead of compiling regular expression patterns for every call. It is linear time complexity relative to the string length but with a very low constant factor because it performs only two searches and one substring operation per call. For high-throughput applications processing millions of strings, this lightweight logic is preferable to regex unless you need advanced pattern matching features like overlapping matches or nested structures.
If you are building a larger framework where you need to strip multiple types of tags dynamically, you might consider integrating this logic into a broader sanitization library. Resources like LaravelCompany often provide community-driven helpers that wrap these native functions to offer more flexible configuration options for string manipulation tasks.