从PHP中的字符串中获取多个子字符串

时间:2016-02-08 21:57:06

标签: php

我想从字符串中提取多个子字符串并放入数组..

例如:

$string = '{[John][16 years old][New York]}{[Michael][22 years old][Las Vegas]}{[Smith][32 years old][Chicago]}';
$array = ["John,16 years old, New York, Mihael, 22 years old, Las Vegas, Smith, 32 years old, Chicago"];

有人想要吗?

3 个答案:

答案 0 :(得分:1)

一个简单的preg_match会这样做:

.grid-data {
  padding: 15px 15px 0 15px;

  div {
    border: 1px solid $off-white-border;
    height: 500px;
  }
  img {
    width: 100%;
  }
}

<强>样本:

http://ideone.com/ReaIOr

<强>更新

要循环播放您可以使用的所有匹配项:

$string = '{[John][16 years old][New York]}{[Michael][22 years old][Las Vegas]}{[Smith][32 years old][Chicago]}';
preg_match_all('/\[(.*?)\]/', $string , $matches, PREG_PATTERN_ORDER);
print_r($matches[1]);

/*
Array
(
    [0] => John
    [1] => 16 years old
    [2] => New York
    [3] => Michael
    [4] => 22 years old
    [5] => Las Vegas
    [6] => Smith
    [7] => 32 years old
    [8] => Chicago
)
*/

答案 1 :(得分:1)

您似乎正在寻找创建单个元素数组,其中包含剥离了某些字符的字符串。为此,您可以使用preg_match_all('/\[(.*?)\]/', $string, $matches, PREG_PATTERN_ORDER); for ($i = 0; $i < count($matches[1]); $i++) { echo $matches[1][$i]; } str_replace

trim

答案 2 :(得分:1)

你会被宠坏的选择!

这是另一个答案,如果你想要提取多个名字,年龄,城市的子串。

这是一个简单的解决方案,使用substrexplodestr_replace

$array = array();
foreach( explode( ']}{[', substr( $string,2,-2 )) as $chunk )
{
    $array[] = str_replace( '][', ',', $chunk );
}
print_r( $array );

eval.in demo

显然,只有在sigle字符串中没有卷曲或方括号时才有效。

首先,它从原始字符串开始和结束括号中删除,然后explode(在数组中转换字符串)字符串][并执行foreach循环获取元素(John][16 years old][New York等...);对于每个元素,它将][替换为,,并将其附加到所需的数组。

全部