PHP求助:提取特定字符串与前一行换行符间的内容
Hey there! Let's work through this string parsing issue together—since you're only a month into PHP, it's totally normal to hit snags with string operations like this. Let's break down what's going wrong and fix it step by step.
First, let's diagnose the problem with your Branding extraction
Your current code for the Branding field uses GetBetween("\n","Branding ",$string), but there are two big issues here:
- The string you're working with has no newline characters (
\n), sostrpos($pool, "\n")returnsfalse. When you addstrlen("\n")to that, it gets cast to0 + 1 = 1, meaning the function starts extracting from the second character of the string all the way to "Branding "—that's why you're getting "Coat: Black Heart Branding" instead of the desired "Heart". - The
GetBetweenfunction as written doesn't handle cases where the start/end markers aren't found, which leads to unexpected behavior.
Here's the fixed solution
First, let's update the GetBetween function to be more robust, so it handles missing markers gracefully. Then we'll adjust the Branding logic to target the exact content you need.
$string = " Coat: Black Heart Branding Looney Leg Heart"; // Improved GetBetween with error handling function GetBetween($start = "", $end = "", $pool) { $startPos = strpos($pool, $start); // If start marker isn't found, return N/A if ($startPos === false) { return "N/A"; } $startPos += strlen($start); $endPos = strpos($pool, $end, $startPos); // If end marker isn't found, take everything from start to end of string return $endPos === false ? trim(substr($pool, $startPos)) : trim(substr($pool, $startPos, $endPos - $startPos)); } // Hair Gloom echo GetBetween("Hair Gloom ", "\n", $string) . " "; // Branding - Extract the word immediately before "Branding" if (preg_match('/(\S+) Branding\b/', $string, $matches)) { echo $matches[1] . " "; } else { echo "N/A "; } // Hoof echo GetBetween("Hoof", "\n", $string) . " "; // Looney Leg echo GetBetween("Looney Leg ", "\n", $string);
What changed?
- Robust
GetBetweenfunction: Now it checks if the start marker exists first, returning "N/A" if it doesn't. It also trims the result to avoid extra spaces, which cleans up output. - Branding extraction: Instead of relying on non-existent newlines, we use a regular expression
/(\S+) Branding\b/to match the non-whitespace characters right before "Branding". This grabs the "Heart" you're expecting. - Output formatting: Added spaces between each result to match your desired output:
N/A Heart N/A Heart.
Testing this code
When you run this, it will output exactly what you're looking for: N/A Heart N/A Heart
内容的提问来源于stack exchange,提问作者Spencer williams
相关产品推荐
相关产品推荐

