Home >Backend Development >PHP Tutorial >How to Extract Substrings in PHP Using Different Delimiter Types?

How to Extract Substrings in PHP Using Different Delimiter Types?

Barbara Streisand
Barbara StreisandOriginal
2025-01-01 07:04:09281browse

How to Extract Substrings in PHP Using Different Delimiter Types?

Determining Substrings in PHP

In PHP, obtaining substrings within specified delimiters can be achieved using various methods. For instance, if the demarcation delimiters are identical at both ends (e.g., [foo] and [/foo]), the following approach will suffice:

function get_string_between($string, $start, $end) {
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) {
        return '';
    }
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

To illustrate, consider the following example:

$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');
echo $parsed; // (result = dog)

Additionally, if the delimiters are unique (e.g., [foo] and [/foo2]), a modified function can be employed:

function get_inner_substring($str, $delim) {
    $results = array();
    $delim_len = strlen($delim);
    $pos = strpos($str, $delim);
    while ($pos !== false) {
        $pos_end = strpos($str, $delim, $pos + $delim_len);
        if ($pos_end !== false) {
            $results[] = substr($str, $pos + $delim_len, $pos_end - $pos - $delim_len);
            $pos = strpos($str, $delim, $pos_end + $delim_len);
        } else {
            break;
        }
    }
    return $results;
}

Using this function, multiple substrings can be extracted from a string separated by different delimiters:

$string = " foo I like php foo, but foo I also like asp foo, foo I feel hero  foo";
$arr = get_inner_substring($string, "foo");
print_r($arr); // (result = ['I like php', 'I also like asp', 'I feel hero'])

The above is the detailed content of How to Extract Substrings in PHP Using Different Delimiter Types?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn