Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to get the middle part of a string in PHP

2 Answers

0 votes
function extractMiddlePart($s, $startChar, $endChar) {
    $startPos = strpos($s, $startChar);
    if ($startPos === false) return '';   // start not found

    $endPos = strpos($s, $endChar, $startPos + 1);
    if ($endPos === false) return '';     // end not found

    return substr($s, $startPos + 1, $endPos - $startPos - 1);
}

$s = "abcde#www!opqrst";

echo extractMiddlePart($s, '#', '!') . "\n";   // www


/*
run:

www

*/


answered Sep 9, 2014 by avibootz
edited 1 day ago by avibootz
0 votes
/*
    Middle‑substring extractor in PHP
    ---------------------------------
    This program demonstrates how to extract the "middle" part of a string.
    The definition of "middle" here is:
        - A substring centered around the midpoint of the string.
        - Caller specifies how many characters to extract.

    Example:
        Input string: "HelloWorld"
        Middle 4 chars → "loWo"

    Architecture notes:
        - A dedicated function handles extraction.
        - Main test suite uses an array of test cases.
        - All logic uses built‑in PHP functions (strlen, substr).
        - No external dependencies.

    Performance notes:
        - substr() and strlen() are O(n) operations.
        - For typical string sizes, performance is excellent.
        - Memory usage is minimal and predictable.

    Security notes:
        - No user input is used; tests are predefined.
        - When adapting for user input, validate encoding and length.

    Pitfalls:
        - For multibyte strings (UTF‑8), use mb_strlen() and mb_substr().
        - Negative lengths or invalid ranges must be handled gracefully.
        - Strings shorter than the requested middle length require fallback logic.

    Edge cases tested:
        - Empty string
        - Very short strings
        - Odd/even lengths
        - Unicode strings (demonstration only; not using mb_* here)
        - Length requests larger than the string
*/

/**
 * Extracts the middle part of a string.
 *
 * @param string $s        Input string.
 * @param int    $length   Number of characters to extract.
 *
 * @return string          Middle substring.
 *
 * Error handling:
 *   - If $length <= 0 → return empty string.
 *   - If string is empty → return empty string.
 *   - If $length >= strlen($s) → return original string.
 *
 * Complexity:
 *   - O(n) due to strlen() and substr().
 */
function getMiddleSubstring(string $s, int $length): string
{
    $total = strlen($s);

    if ($length <= 0 || $total === 0) {
        return "";
    }

    if ($length >= $total) {
        return $s;
    }

    // Compute midpoint index
    // Example: length 10 → midpoint = 5
    $mid = intdiv($total, 2);

    // Compute start index so substring is centered
    // Example: want 4 chars → start = 5 - 2 = 3
    $start = $mid - intdiv($length, 2);

    // Ensure start is within bounds
    if ($start < 0) {
        $start = 0;
    }

    if ($start + $length > $total) {
        $length = $total - $start;
    }

    return substr($s, $start, $length);
}

/*
    Test suite
    ----------
    Each test case is an associative array:
        - 'input'  → string
        - 'length' → requested middle length
*/
$tests = [
    ["input" => "",                 "length" => 3],  // empty string
    ["input" => "A",                "length" => 1],  // single char
    ["input" => "AB",               "length" => 1],  // even length
    ["input" => "HelloWorld",       "length" => 4],  // typical case
    ["input" => "MiddleTest",       "length" => 5],  // odd length
    ["input" => "Short",            "length" => 10], // request longer than string
    ["input" => "ABCDE",            "length" => 2],  // simple even
    ["input" => "ABCDE",            "length" => 3],  // simple odd
    ["input" => "abcde#www!opqrst", "length" => 3],  // simple odd
];

echo "Middle‑substring extraction tests:\n\n";

foreach ($tests as $t) {
    $input  = $t["input"];
    $length = $t["length"];
    $result = getMiddleSubstring($input, $length);

    echo "Input: '{$input}' | Length: {$length} → Middle: '{$result}'\n";
}


/*
run:

Middle‑substring extraction tests:

Input: '' | Length: 3 → Middle: ''
Input: 'A' | Length: 1 → Middle: 'A'
Input: 'AB' | Length: 1 → Middle: 'B'
Input: 'HelloWorld' | Length: 4 → Middle: 'loWo'
Input: 'MiddleTest' | Length: 5 → Middle: 'dleTe'
Input: 'Short' | Length: 10 → Middle: 'Short'
Input: 'ABCDE' | Length: 2 → Middle: 'BC'
Input: 'ABCDE' | Length: 3 → Middle: 'BCD'
Input: 'abcde#www!opqrst' | Length: 3 → Middle: 'ww!'

*/

 



answered Dec 3, 2024 by avibootz
edited 1 day ago by avibootz

Related questions

1 answer 237 views
2 answers 154 views
2 answers 273 views
1 answer 249 views
3 answers 236 views
4 answers 329 views
...