PHP String Manipulation: Multiple Approaches to Truncate Text Based on Specific Substrings

Nov 21, 2025 · Programming · 9 views · 7.8

Keywords: PHP string manipulation | strpos function | substr function | text truncation | programming techniques

Abstract: This article provides an in-depth exploration of various technical solutions for removing all content after a specific substring in PHP. By analyzing the core implementation principles of combining strpos and substr functions, it details modern alternatives using strstr function, and conducts cross-platform comparisons with Excel text processing cases. The article includes complete code examples, performance analysis, boundary condition handling, and practical application scenarios, offering comprehensive string operation references for developers.

Problem Background and Requirement Analysis

In PHP development, truncating text data is a common requirement. A typical scenario involves extracting key information from strings containing specific delimiters. For example, removing "By" and all subsequent content from "Posted On April 6th By Some Dude" to retain only "Posted On April 6th".

Core Solution: strpos and substr Combination

PHP offers multiple string manipulation functions, with the combination of strpos() and substr() being the most fundamental and efficient approach. This solution works by using strpos() to locate the starting position of the target substring, then employing substr() to extract all characters from the beginning of the string up to that position.

Specific implementation code:

$originalString = "Posted On April 6th By Some Dude";
$delimiter = "By";
$resultString = substr($originalString, 0, strpos($originalString, $delimiter));
echo $resultString; // Output: Posted On April 6th

Code execution flow analysis:

  1. strpos($originalString, $delimiter) returns the starting position index of substring "By" in the original string
  2. substr($originalString, 0, position) extracts a substring of specified length starting from index 0
  3. Since strpos() returns the starting position of the delimiter, using this value directly as the length parameter excludes the delimiter itself

Alternative Approach: Advanced Usage of strstr Function

For PHP 5.3 and later versions, the strstr() function provides a more concise solution. This function supports a third parameter $before_needle, which when set to true, returns the portion before the delimiter.

Implementation example:

$originalString = "Posted On April 6th By Some Dude";
$resultString = strstr($originalString, 'By', true);
echo $resultString; // Output: Posted On April 6th

The advantage of this method lies in its concise and intuitive code, though PHP version compatibility requirements must be considered.

Boundary Conditions and Error Handling

In practical applications, various boundary cases must be considered to ensure code robustness:

Handling cases where delimiter doesn't exist:

$originalString = "Posted On April 6th";
$delimiter = "By";
$position = strpos($originalString, $delimiter);

if ($position !== false) {
    $resultString = substr($originalString, 0, $position);
} else {
    $resultString = $originalString; // Delimiter doesn't exist, return original string
}

echo $resultString; // Output: Posted On April 6th

Case sensitivity handling:

// Default strpos is case-sensitive
$position = strpos($originalString, 'by'); // Returns false

// For case-insensitive search, use stripos
$position = stripos($originalString, 'by'); // Returns correct position

Cross-Platform Comparison: String Truncation in Excel

String truncation operations share similar implementation logic across different programming environments and tools. Referencing Excel's text processing functionality reveals comparable patterns:

Excel formula implementation:

=LEFT(A2, SEARCH(",", A2) - 1)

This aligns closely with the PHP solution logic:

Performance Analysis and Best Practices

Through performance testing and code analysis of the two main approaches, the following conclusions can be drawn:

strpos+substr combination:

strstr approach:

Practical Application Scenario Extensions

Based on core string truncation techniques, extensions to more complex application scenarios are possible:

Multiple delimiter handling:

function removeAfterMultiple($string, $delimiters) {
    $minPosition = strlen($string);
    
    foreach ($delimiters as $delimiter) {
        $position = strpos($string, $delimiter);
        if ($position !== false && $position < $minPosition) {
            $minPosition = $position;
        }
    }
    
    return $minPosition < strlen($string) ? substr($string, 0, $minPosition) : $string;
}

$result = removeAfterMultiple("Posted On April 6th By Some Dude", ["By", "On"]);
// Returns: Posted

Variant that preserves delimiter:

// If delimiter needs to be included in result
$position = strpos($originalString, $delimiter);
if ($position !== false) {
    $resultString = substr($originalString, 0, $position + strlen($delimiter));
}

Summary and Recommendations

The basic pattern for removing content after a specific substring in PHP is achieved through the combination of location and extraction operations. Developers should choose appropriate solutions based on specific requirements: for scenarios requiring high general compatibility, the strpos()+substr() combination is recommended; for modern PHP environments prioritizing code conciseness, the before_needle parameter of strstr() can be considered.

Regardless of the chosen approach, comprehensive consideration of boundary condition handling is essential, including cases where delimiters don't exist, empty string inputs, multi-byte character support, and other special circumstances, to ensure stable code operation across various environments.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.