[英]PHP : Find array pattern in string using regex
I have a string like this it is array pattern : 我有一个像这样的字符串,它是数组模式:
["foo","bar","bra bra","xxx123"]
How can i get the foo
, bar
, bra bra
, xxx123
Pattern is ["","",""]
我如何获取foo
, bar
, bra bra
, xxx123
模式为["","",""]
Since php 5.4 that is a shorthanded way of doing an array. 从php 5.4开始,这是执行数组的一种简便方法。
See: http://docs.php.net/manual/en/language.types.array.php 参见: http : //docs.php.net/manual/en/language.types.array.php
Specific quote: 具体报价:
As of PHP 5.4 you can also use the short array syntax, which replaces array() with []. 从PHP 5.4开始,您还可以使用短数组语法,该语法用[]替换array()。
Therefore the basic way is like any other array: 因此,基本方法类似于任何其他数组:
$arr = ["foo","bar"];
foreach($arr AS $arg){
echo $arg; //you can add your logic here for comma seperating or beautifying
}
You can do it without regex: 您可以不使用正则表达式:
$result = explode('","', trim($str, '[]"'));
or with regex: 或使用正则表达式:
if (preg_match_all('~"([^"]*)"~', $str, $m))
$result = $m[1];
or a regex to handle escaped quotes: 或用于处理转义引号的正则表达式:
if (preg_match_all('~"([^"\\\]*(?s:\\\.[^"\\\]*)*)"~', $str, $m))
$result = $m[1];
I suspect, that a regex might be the wrong tool - try explode
! 我怀疑正则表达式可能是错误的工具-尝试explode
!
$string='["foo","bar","bra bra","xxx123"]';
//Remove start/end
if (substr($string,0,2)!='["') die('Malformed start!');
if (substr($string,-2)!='"]') die('Malformed end!');
$string=substr($string, 2, -2);
//Now explode
$array=explode('","', $string);
print_r($array);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.