如何获得两个字符[string]之间的字符串?的PHP [英] How can I get string between two characters [string] ? PHP

查看:101
本文介绍了如何获得两个字符[string]之间的字符串?的PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$string1 = "This is test [example]";
$string2 = "This is test [example][2]";
$string3 = "This [is] test [example][3]";

如何获得以下结果?

For $string1 -> example
For $string2 -> example*2
For $string3 -> is*example*3

推荐答案

preg_match_all('/\[([^\]]+)\]/', $str, $matches);

php > preg_match_all('/\[([^\]]+)\]/', 'This [is] test [example][3]', $matches);
php > print_r($matches);
Array
(
    [0] => Array
        (
            [0] => [is]
            [1] => [example]
            [2] => [3]
        )

    [1] => Array
        (
            [0] => is
            [1] => example
            [2] => 3
        )

)

这是rregex的解释:

And here's the explanation for the rregex:

\[ # literal [
( # group start
    [^\]]+ # one or more non-] characters
) # group end
\] # literal ]

这篇关于如何获得两个字符[string]之间的字符串?的PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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