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
Release: 2025-01-01 07:04:09
Original
273 people have browsed it

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);
}
Copy after login

To illustrate, consider the following example:

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

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;
}
Copy after login

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'])
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template