PHP在标签之间获取字符串[一个字符串中包含多个标签] [英] PHP get string between tag [Multiple tag in one string]

查看:307
本文介绍了PHP在标签之间获取字符串[一个字符串中包含多个标签]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜索很多东西,但是找不到与我的问题类似的东西.我已经找到了这个链接,但我认为他们并没有真正回答问题.

I've been searching a lot but i cannot find anything similar to my problem. I've found this link but i don't think they really answered the question.

假设我有这个字符串

$my_string = "I am with a [id]123[/id] and [id]456[id]";

我想获取[id] [/id]之间的所有数字.我只有这个功能来获取两者之间的字符串.

I want to get all the number between [id][/id]. I only have this function to get the string between.

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

$fullstring = 'I am with a [id]123[/id] and [id]456[id]';
$parsed = get_string_between($fullstring, '[id]', '[/id]');

但是此函数仅返回在$ fullstring上找到的第一个字符串.也许我可以得到123,456或数组形式为array('123','456').我真的很坚持.

But this function only returns the first string found on $fullstring. Maybe i can get 123,456 or in array form array('123','456'). I really am stuck with this.

推荐答案

您可以简单地使用PHP的preg_match_all函数以及以下正则表达式

You can simply use preg_match_all function of the PHP along with following regex

~\[id\](.*?)\[\/id\]~

$my_string = "I am with a [id]123[/id] and [id]456[/id]";
preg_match_all("~\[id\](.*?)\[\/id\]~",$my_string,$m);
print_r($m[1]);

这篇关于PHP在标签之间获取字符串[一个字符串中包含多个标签]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆