PHP字符串截取:在指定字符串前反向查找首个'a'并截断前置内容
Solution for Your String Manipulation Task
Got it, let's work through this step by step—you can totally pull this off with PHP's built-in string functions, no fancy stuff needed. Here's how to get exactly the result you want:
Step-by-Step Breakdown
- Locate the position of
$string2("EXAMPLE") in your main string$string1usingstrpos(). Always add a check to handle cases where "EXAMPLE" might not exist (to avoid errors). - Grab the substring before "EXAMPLE" and find the last occurrence of 'a' in that segment—this is equivalent to searching backwards from "EXAMPLE" to the first 'a'.
- Extract the desired substring starting from that 'a' position, all the way to the end of "EXAMPLE".
Full Code Example
<?php $string1 = "...This is a very long an complex string . This is a very long string. This is a very long EXAMPLE string. This is a very long string. This is a very long string."; $string2 = "EXAMPLE"; // 1. Find where EXAMPLE starts in the main string $exampleStartPos = strpos($string1, $string2); if ($exampleStartPos === false) { echo "Error: 'EXAMPLE' not found in the string"; exit; } // 2. Get the part of the string before EXAMPLE, then find the last 'a' there $substringBeforeExample = substr($string1, 0, $exampleStartPos); $firstBackwardAPos = strrpos($substringBeforeExample, 'a'); if ($firstBackwardAPos === false) { echo "Error: No 'a' found before 'EXAMPLE'"; exit; } // 3. Extract from the found 'a' to the end of EXAMPLE $resultLength = $exampleStartPos - $firstBackwardAPos + strlen($string2); $finalResult = substr($string1, $firstBackwardAPos, $resultLength); echo $finalResult; // Output: "a very long string. This is a very long EXAMPLE" ?>
Why This Works
strpos()gives us the starting index of "EXAMPLE"—critical for knowing where to start our backward search.- By taking the substring before "EXAMPLE" and using
strrpos()to find the last 'a', we're effectively searching backwards from the start of "EXAMPLE" without dealing with the tricky offset behavior ofstrrpos()'s third parameter (which can be confusing for new users). - The final
substr()calculates exactly how long the desired segment is: from the 'a' position to the end of "EXAMPLE", so we get the exact output you need.
内容的提问来源于stack exchange,提问作者redsunset
相关产品推荐
相关产品推荐

