PHP:使用正则表达式在字符串中查找数组模式
问题描述:
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 ["","",""]
我有一个像这样的字符串它是数组模式: p>
[“foo”,“bar”,“bra bra”,“xxx123”]
code> pre>
如何获取 foo code>, bar code>, bra bra code>, xxx123 code>
Pattern是 [“”,“”,“”] code> p >
div>
答
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];
答
Since php 5.4 that is a shorthanded way of doing an array.
See: 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 [].
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
}
答
I suspect, that a regex might be the wrong tool - try 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);