如何截取两个|符号间的字符串?已获取首段,求第二段、第三段提取方法
Hey there! Let's figure out how to grab those second and third strings for you. Since you're already using substr() and strpos() to get the first part, I'll walk you through two solid approaches—one that builds on your existing code, and another way that's even simpler.
explode() (The Simplest Way) This method splits your entire string into an array using the exact separator (" | ", including the spaces around the pipe), then you can just access the array elements directly:
$WholeString = "FirstString | 2ndString | 3rdString"; // Split the string by the " | " separator $stringParts = explode(" | ", $WholeString); $firstString = $stringParts[0]; // Output: "FirstString" $secondString = $stringParts[1]; // Output: "2ndString" $thirdString = $stringParts[2]; // Output: "3rdString"
This is super straightforward and easy to read—perfect if you don't need to manually track character positions.
substr() + strpos() Approach If you want to stick with the functions you're already using, you can chain strpos() calls to find the positions of both pipes, then extract the middle and final parts:
$WholeString = "FirstString | 2ndString | 3rdString"; // Your existing code to get the first string $firstPipePosition = strpos($WholeString, '|'); $firstString = substr($WholeString, 0, $firstPipePosition); // Get the second string: start right after the first pipe + space, end at the second pipe $startOfSecond = $firstPipePosition + 2; // +2 to skip the " | " (pipe + space) $secondPipePosition = strpos($WholeString, '|', $startOfSecond); $secondString = substr($WholeString, $startOfSecond, $secondPipePosition - $startOfSecond); // Get the third string: start right after the second pipe + space, go to the end of the string $startOfThird = $secondPipePosition + 2; $thirdString = substr($WholeString, $startOfThird);
Here, we use the third parameter of strpos() to start searching for the second pipe after the first one, so we don't accidentally find the first pipe again.
Quick Tip for Inconsistent Formatting
If your input string might have messy spacing around the pipe (like "FirstString|2ndString | 3rdString"), use preg_split() to handle any number of spaces before/after the pipe:
$stringParts = preg_split('/\s*\|\s*/', $WholeString); // This splits on pipes with zero or more spaces on either side
内容的提问来源于stack exchange,提问作者user8782882

