我有一个字符串,其中包含字段占位符。我需要通过这些占位符拆分字符串,并将字符串和占位符返回到单个数组中。
例如,如果我有字符串:
Ohio is one of the original [s] in the northwest territory. [s] and [s] were also part of the northwest territory. Which states are missing [a]?
我希望看到它分成一个数组:
[0] => Ohio is one of the original
[1] => [s]
[2] => in the northwest territory.
[3] => [s]
[4] => and
[5] => [s]
[6] => were also part of the northwest territory. Which states are missing
[7] => [a]
[8] => ?
为了满足那些假设我们从未阅读过手册的人,这里有一些我尝试过的代码......我只是无法获得上面列出的格式的数组。我最接近的是这个,但它仍然比我在阵列的某些部分需要更多的文本。我承认,我从未成为REGEX专家,所以感谢您的帮助。
我匹配[]中包含的任何一个字符,即[a],[b],[e]等。
preg_match_all("/(.*?)\[(.)\](.*?)/",$string,$x,PREG_SET_ORDER);
print_r($x);
答案 0 :(得分:1)
虽然我原本被rjdown的令人讨厌的答案所冒犯,但我确实重新审视了我的所有例子并找到了一个有效的选项。包括“-1”是最后的诀窍。谢谢rjdown
$results =preg_split("/(\[.\])/i",$string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
结果是:
Array
(
[0] => Ohio is one of the original
[1] => [s]
[2] => in the northwest territory.
[3] => [s]
[4] => and
[5] => [s]
[6] => were also part of the northwest territory. Which states are missing
[7] => [a]
[8] => ?
)