You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. The string you're working with has no newline characters (\n), so strpos($pool, "\n") returns false. When you add strlen("\n") to that, it gets cast to 0 + 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".
  2. The GetBetween function 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?

  1. Robust GetBetween function: 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.
  2. 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.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:07:58