[英]php preg_split split string to array from square brackets
I want to split the string from square brackets without removing any character. 我想从方括号中拆分字符串而不删除任何字符。 I tried the below code but it's not working for me.
我尝试了以下代码,但不适用于我。
$value = "<p> Lorem ipsum dolor [State] sit amet, consectetur [City] adipisicing [TopJob7] elit, sed do eiusmod [JobType]</p>";
$tagsReplace = preg_split('/[\[]*[\][]/U', $value, -1);
echo '<pre>';
print_r( $tagsReplace );
exit;
When I run the above code I got the output like 当我运行上面的代码时,我得到的输出像
Array
(
[0] => <p> Lorem ipsum dolor
[1] => State
[2] => sit amet, consectetur
[3] => City
[4] => adipisicing
[5] => TopJob7
[6] => elit, sed do eiusmod
[7] => JobType
[8] => </p>
)
I want output like below. 我想要下面的输出。
Array
(
[0] => <p> Lorem ipsum dolor
[1] => [State]
[2] => sit amet, consectetur
[3] => [City]
[4] => adipisicing
[5] => [TopJob7]
[6] => elit, sed do eiusmod
[7] => [JobType]
[8] => </p>
)
Please help me where I did a mistake. 请帮我弄错了地方。
Your pattern [\\[]*[\\][]
matches 0+ times an opening bracket and then either a opening or closing bracket giving you either a [
or n ]
您的模式
[\\[]*[\\][]
匹配0+乘以左括号,然后是右括号或右括号,为您提供[
或n ]
To keep the delimiters you could capture in a group matching from [
to ]
and match what is in between using a negated character class matching not a closing bracket. 为了保持定界符,您可以捕获从
[
到]
匹配的组,并使用否定的字符类匹配而不是右括号匹配两者之间的内容。
Use the PREG_SPLIT_DELIM_CAPTURE
flag to keep the delimiter. 使用
PREG_SPLIT_DELIM_CAPTURE
标志保留定界符。
Note that you don't need the /U
flag. 请注意,您不需要
/U
标志。
(\[[^]]+\])
Explanation 说明
(
Capturing group (
捕获组
\\[
Match [
\\[
匹配[
[^]]+
Match 1+ times not a ]
[^]]+
匹配1+次而不是]
\\]
Match ]
\\]
匹配]
)
Close group )
封闭小组 Regex demo | 正则表达式演示 | Php demo
PHP演示
For example: 例如:
$value = "<p> Lorem ipsum dolor [State] sit amet, consectetur [City] adipisicing [TopJob7] elit, sed do eiusmod [JobType]</p>";
$tagsReplace = preg_split('/(\[[^]]+\])/', $value, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r( $tagsReplace );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.