Using regex to find value between square brackets [duplicate]

不打扰是莪最后的温柔 提交于 2020-01-07 03:14:25

问题


I want to find the value inside square brackets. Let's say I have a string like this

$str = "This is a test string. I want to get value between [this] and [/this]";

So, to explain it pretty clearly, I want to find [this] and [/this] and then the 'and' between them. I found some threads here about finding the value inside square brackets but that's not exactly my case, and it did not help. Regex to me is Hebrew to me if you know what I mean.


回答1:


You could use the below regex,

\[.*?\][^\]]*\]

DEMO

Your code would be,

<?php
$str = "This is a test string. I want to get value between [this] and [/this]";
$regex = '~\[.*?\][^\]]*\]~';
if (preg_match($regex, $str, $m)) {
    $yourmatch = $m[0]; 
    echo $yourmatch;
    }
?> //=>  [this] and [/this]



回答2:


You can use this regex:

\[[^]]*\][^[]*\[[^]]*\]

Online Regex Demo



来源:https://stackoverflow.com/questions/24553265/using-regex-to-find-value-between-square-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!