php getneedbetween,PHP Get Text Between Tags + The Tags Themselves

本文介绍了一个函数,用于在给定文本中查找并返回指定标签(如[tag]hitodog[/hi])内的内容,同时保持标签结构。作者希望实现的功能能够检测开始和结束标签,并允许用户修改内容和标签,如将[tag]和[/tag]替换为and。
摘要由CSDN通过智能技术生成

原文:

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.

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值