简体   繁体   English

PHP 获取标签之间的文本 + 标签本身

[英]PHP Get Text Between Tags + The Tags Themselves

I want to get all text between [tag] and [/tag] including the tags.我想获取 [tag] 和 [/tag] 之间的所有文本,包括标签。

So this sentence.所以这句话。

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

Using this function.使用这个 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.因此,如果 [tag] 和 [/tag] 都存在于文本周围,则将其更改为文本及其周围。

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.我可以用 str_replace 完成它们,但我不知道如何结合搜索开始和结束标签,并替换它们。

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.试试下面的代码,基本上你需要检测开始标签和结束标签,并根据需要在 substr 中包含标签。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM