Skip to content
Advertisement

PHP Get Text Between Tags + The Tags Themselves

I want to get all text between [tag] and [/tag] including the tags.

So this sentence.

The cat said [tag]hi to dog[/hi] at the park.

Using this function.

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);
}

I can return the text between the tags. But I want the tags also. Basically I want to scan my text for tags to make sure there is both a start and ending tag. Then allow me to edit the content and the tags. So change the [tag] and [/tag] to and around the text if both exist around the text.

I can do they with str_replace, but I don’t know how to combine the search for the open and ending tags, and replacing them.

Advertisement

Answer

Try the following code, basically you need to detect the starting tag and ending tag, and do the substr include the tags as you want.

function get_string_between($string, $start, $end){
    $posStart = strpos($string, $start);
    if (!($posStart !== false)) return '';
    $posEnd = strpos($string, $end);
    if (!($posEnd !== false)) return '';
    $len = strlen($end);
    return substr($string, $posStart, $posEnd - $posStart + $len);
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement