2013-03-04 45 views
0

我有一个字符串:得到一个字符串中的字符串 - PHP

[gallery ids="2282,2301,2302,2304,2283,2303,2285,459,1263,469,471,1262,1261,472,608,467,607,606,466,460"] 

ids会有所不同,但我怎么能(在PHP)获取值?

RegExps不是我的强项,但我想我们可以检查单词ids后面的引号内的所有内容吗?

+0

'strpos' +'substr'怎么样? – zerkms 2013-03-04 23:50:07

回答

2

我认为一个简单的解决方案,而比使用preg_match简单的是explode字符串使用"作为分隔符,其中id将是第二个元素(索引1)。

$string = '[gallery ids="2282,2301,2302,2304,2283,2303,2285,459,1263,469,471,1262,1261,472,608,467,607,606,466,460"]'; 

$array = explode('"', $string); 

$ids = explode(',', $array[1]); 

这可以从PHP 5.4很优雅,其中取消引用已添加功能阵列:

$string = '[gallery ids="2282,2301,2302,2304,2283,2303,2285,459,1263,469,471,1262,1261,472,608,467,607,606,466,460"]'; 

$ids = explode(',', explode('"', $string)[1]); 

这个拥有超过preg_match的好处是,它并不重要的值是 - 他们可以是数字或字母或其他符号。

+0

+1为优雅 – 2013-03-05 01:06:42

+0

很好的答案,但preg_match可以匹配任何东西。这对于这个简单的任务来说可能是过度的。 – 2013-03-05 06:25:35

+0

是的,但您需要*知道*这些值的模式。 '爆炸'你不这样做,所以它更具有可扩展性。 – MichaelRushton 2013-03-05 09:29:01

5

正则表达式:preg_match_all(/\d+/,$string,$matches);

解释演示在这里:http://regex101.com/r/fE4fE6

+0

感谢您的链接:] – 2013-03-04 23:56:09

+0

不客气@MichelFeldheim伟大的工具 – 2013-03-05 00:02:00

0

如果你想要一个非正则表达式的解决方案,你可以做这样的事情:

$str = ...; 

$start = strpos($str, '"') + 1; // find opening quotation mark 
$end = strpos($str, '"', $start); // find closing ''  '' 

$ids = explode(",", substr($str, $start, $end - $start));